PHP json_decode无法正常工作

时间:2011-07-15 15:17:48

标签: php json

我正在尝试使用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的回答,它仍然无法正常工作。任何帮助都将非常受欢迎,同时保持阵列样式而不是进入对象。

2 个答案:

答案 0 :(得分:5)

除了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");

输出:

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

All done.

答案 1 :(得分:2)

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

$json_information[0]['channel']['image_url_large']
相关问题