繁体   English   中英

PHP json_decode 无法正常工作

[英]PHP json_decode not working properly

我正在尝试使用 PHP 的 json_decode function 从 json object 中获取特定值。 下面的示例代码:

foreach ($streams as &$i) {
        $chan = "http://api.justin.tv/api/stream/list.json?channel=" . $i;
        $json = file_get_contents($chan);   //Turns the gathered file information into a string for searching purposes.
        echo $json . " End of json variable.<br>";
        $exist = strpos($json, 'name');     // Search the file/json object for the name attribute
        if($exist) {                        //  Check to see if a name existed and if so add it to the live streams and get the image.
            echo " <a href=\"http://justin.tv/" . $i . "\">" . $i . "</a> <br>";
            $liveStreams[$count] = $i;
            $json_information = json_decode($json,true);
            $image[$count] = $json_information[0]['channel']['image_url_large'];
            echo "Image link should appear: " . $image[count];
            $count++;
        }
    }   

所以我要做的首先是从代码前面提供的列表中收集哪些流是活动的。 其次,如果 stream 处于活动状态,请显示一个指向页面的链接以供查看(目前是 justin.tv stream 本身)。 目前有效的是只有实时流将显示链接到它们。 我需要弄清楚为什么解码后我无法访问 image_url_large 变量。 这最终将成为 stream 的缩略图。

我已经查看了各个地方应该可行的方法,甚至在stackoverflow上我也看到了以下线程:

json 在 php 中解码

我尝试像 nickf 的回答那样做,但它仍然无法正常工作。 任何帮助以及保持在数组样式中而不是进入对象都将不胜感激。

除了愚蠢地使用 strpos()(您似乎声称这是别人的想法)之外,您似乎只需要仔细调试。

做这样的事情:

$data = json_decode($json,true);
echo "<PRE>";
var_dump($data); die();

现在您可以看到 API 提供给您的数据结构。

查看数组的结构。 例如,请注意$data['image_url_large']不存在。 但是,有$data[0]['channel']['image_url_large']

另请注意,如果字符串“name”存在于 json-string 中的任何位置,则会给出误报,而不是愚蠢的 strpos() 调用,您可以执行以下操作:

$exists = ! empty($data[0]['name']);

编辑这里有一些代码希望能帮助你:

    <?php 
//if you don't do this, you're flying blind.
ini_set('display_errors',1);
error_reporting(E_ALL);

//list.json is a copy of the data from the URL you posted.
$json = file_get_contents('./list.json');   

//decode the data
$data = json_decode($json,true);

//uncomment this if you're not sure of what the json's structure is.
#echo "<PRE>";var_dump($data);die();

//check for the existence of a "name" key in the first item.
$exist = ! empty($data[0]['name']);

echo "Exist?:";

if ($exist) { 
    echo " yes\n";
}else{
    echo " no\n";
}

//output the image url:
echo $data[0]['channel']['image_url_large'];

//say goodbye
die("\n\nAll done.\n");

OUTPUT:

$ php test.php 
Exist?: yes
http://static-cdn.jtvnw.net/jtv_user_pictures/beastyqt-profile_image-c5b72ccf47b74ed2-300x300.jpeg

All done.

使用 var_dump() 检查返回的 json object。 从您的示例中,您似乎需要以下内容:

$json_information[0]['channel']['image_url_large']

暂无
暂无

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

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