2012-02-18 181 views
0

我明白如何解析json與PHP,但我不明白如何閱讀它的眼睛。有人可以幫我解決這個問題嗎?解析JSON結果

這裏是我的代碼

<?php 
$json = file_get_contents('json.txt'); 
$json_output = json_decode($json); 

foreach ($json_output->query as $stf) 
{ 
    echo "{$stf->response->domains->name}\n"; 
} 
?> 

這裏是JSON結果

{ "query" : { "host" : "test.com", 
     "tool" : "pro" 
    }, 
    "response" : { "domain_count" : "13", 
     "domains" : [ { "last_resolved" : "2012-01-11", 
      "name" : "test1.com" 
      }, 
      { "last_resolved" : "2012-01-11", 
      "name" : "test2.com" 
      }, 

的樣品正如你可以看到我試着查詢 - >應答爲>域 - >名稱,它沒」工作。

我會如何嘗試名稱?

預先感謝您

回答

3

query->response->domains是索引數組,所以你需要得到一個指標,說[0],然後得到了->name

echo $stf->response->domains[0]->name."\n"; 
1
foreach ($json_output->query->response->domains as $domain) 
{ 
    echo $domain->name; 
} 

研究這個http://json.org/

0

如果你想用眼睛看它,它可能會幫助重新格式化:

{ 
    "query" : { 
    "host" : "test.com", 
    "tool" : "pro" 
    }, 
    "response" : { 
    "domain_count" : "13", 
    "domains" : [{ 
     "last_resolved" : "2012-01-11", 
     "name" : "test1.com" 
    },{ 
     "last_resolved" : "2012-01-11", 
     "name" : "test2.com" 
    }] 
    } 
}