PHP json_decode无法正常工作
|
我试图使用
PHP的json_decode函数从json对象获取特定值.
示例代码如下: 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++;
}
}
所以我要做的就是首先从代码中前面提供的列表中收集哪些流是活动的.其次,如果流是实时的,则显示指向要查看的页面的链接(当前是justin.tv流本身).目前的工作原理是只会显示带有链接的实时流.我需要的是弄清楚为什么解码后我无法访问image_url_large变量.这将最终成为流的缩略图. 我已经查看了应该工作的各个地方甚至在stackoverflow上我看到了以下线程: json decode in 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 " yesn";
}else{
echo " non";
}
//output the image url:
echo $data[0]['channel']['image_url_large'];
//say goodbye
die("nnAll done.n");
OUTPUT: $php test.php Exist?: yes http://static-cdn.jtvnw.net/jtv_user_pictures/beastyqt-profile_image-c5b72ccf47b74ed2-300x300.jpeg All done. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
