简体   繁体   English

json解析php中的响应

[英]json parsing response in php

I am getting NULL for all my JSON data here is my code 我所有的JSON数据都为NULL,这是我的代码

$jsons1 = file_get_contents($api_url); // returns JSON
        $jsons=json_decode($jsons1);

        foreach ($jsons as $json)
        {
        echo "\n";
        echo "<ul>";
        echo "<li>";
        echo "\nTitle : ".$json->title."\n";
        echo "\nContent: ".$json->content."\n";
        echo "</li>";
        echo "</ul>";
        }

I am unable to fetch it like $json->title, Am i missing something? 我无法像$ json-> title一样获取它,我丢失了什么吗?

The output is 输出是

 - Title : Content: 

Please help in this regard 请帮助这方面

here is output of $jsons1 variable 这是$jsons1变量的输出

{"results":[{"title": "Temp, Russia - Wikipedia, the free encyclopedia","kwic": "Coordinates : 52°03′N 39°44′E  /  52.05°N 39.733°E  / 52.05; 39.733  tenmp ( Russian : УÑмань ) is a town and the administrative center of ...","content": "","url": "http://en.wikipedia.org/wiki/sdfds,_Russia","iurl": "","domain": "en.wikipedia.org","author": "","news": false,"votes": "1","date": 1357744155518,"related":[]}],"query": "tenp","suggestions":[],"count":96,"start":1,"length":10,"time": "412"}

Try as 尝试为

$j = '{"results":[{"title": "Temp, Russia - Wikipedia, the free encyclopedia","kwic": "Coordinates : 52°03′N 39°44′E  /  52.05°N 39.733°E  / 52.05; 39.733  tenmp ( Russian : УÑмань ) is a town and the administrative center of ...","content": "","url": "http://en.wikipedia.org/wiki/sdfds,_Russia","iurl": "","domain": "en.wikipedia.org","author": "","news": false,"votes": "1","date": 1357744155518,"related":[]}],"query": "tenp","suggestions":[],"count":96,"start":1,"length":10,"time": "412"}';

$data = json_decode($j,true);

foreach ($data["results"] as $key=>$val){
    echo "\n";
    echo "<ul>";
    echo "<li>";
    echo "\nTitle : ".$val["title"]."\n";
    echo "\nContent: ".$val["content"]."\n";
    echo "</li>";
    echo "</ul>";
}

Right now there is only one data in results element so looping is better if there are more. 现在, 结果元素中只有一个数据,因此如果有更多数据,循环会更好。

You have object results containing your datas.. 您有包含数据的对象结果。

So you have just to fix your Foreach statement ..> 因此,您只需要修复您的Foreach语句即可。

    foreach ($jsons->results as $json) { ... }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM