json_decode

时间:2015-05-19 04:41:16

标签: php json

我是PHP新手,我试图用它来过滤“纽约时报”的信息。文章搜索API。我仍然在努力弄清楚如何能够提取出来的网络网址#34;和"片段"通过查看类似的question,即使是JSON响应也是如此。我使用json_decode将响应转换为关联数组。这是我的代码

   $data = file_get_contents($queryURL);
    $jsondata = json_decode($data, true);
    if (count($jsondata) != 0) 
    {
        foreach($jsondata['response']as $key => $value) 
        {
          echo "Key: " . $key . " Value: " . $value . " <br>";
        } 
    }

这只打印出单词&#34; array&#34;,&#34; ok&#34;和&#34;版权&#34;。

这是json的一个样本:

"response": {
    "meta": {
        "hits": 25,
        "time": 332,
        "offset": 0
    },
    "docs": [
        {
            "web_url": "http://thecaucus.blogs.nytimes.com/2012/01/01/virginia-attorney-general-backs-off-ballot-proposal/",
            "snippet": "Virginia's attorney general on Sunday backed off of a proposal to loosen the state's ballot access rules to allow more Republican presidential candidates to qualify.",
            "lead_paragraph": "DES MOINES -- Virginia's attorney general on Sunday backed off of a proposal to loosen the state's ballot access rules to allow more Republican presidential candidates to qualify.",
            "abstract": "Virginia's attorney general on Sunday backed off of a proposal to loosen the state's ballot access rules to allow more Republican presidential candidates to qualify.",
            "print_page": null,
            "blog": [ ],
            "source": "The New York Times",
            "multimedia": [ ],
            "headline": {
                "main": "Virginia Attorney General Backs Off Ballot Proposal",
                "kicker": "The Caucus"
            },

2 个答案:

答案 0 :(得分:4)

试试这个。您需要遍历每个文档

foreach ($jsondata['response']['docs'] as $doc) {
    echo "web_url: " . $doc['web_url'] . " snippet: " . $doc['snippet'];
}

答案 1 :(得分:2)

循环浏览$jsondata['response']

然后当您的 $ key meta 时(类似于其他键以及 docs 等), $ value 数组

array(
"hits"=> 25,
        "time"=> 332,
        "offset"=> 0
)

因此,当您尝试回显此 $ value 时,它会在php中打印数组作为 echo 的属性,以将数组打印为字符串的&#34;阵列&#34;

我希望这能说清楚你做错了什么!

你可能需要做这样的事情

foreach($jsondata['response']as $key => $value) 
        {
          // check if $jsondata['response'][$key] is an array using is_array()
          // handle as per array

        } 

了解is_array