PHP json_decode 无法正常工作

标签 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 变量。这最终将成为流的缩略图 View 。

我查看了不同的地方以寻找应该有效的方法,甚至在 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 字符串中的任何位置,则会给出误报,而不是愚蠢的 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.

关于PHP json_decode 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6709293/

相关文章:

php - 如何列出带有相关图像的 wp 帖子?

arrays - 如何将非标准索引的数组转换为json?

jquery - parsererror 语法错误 : Unexpected token < - Load Partial View using jQuery Ajax in ASP. NET MVC 4

java - 用java合并json对象

php - 如何更改数组中每个键的第一个字符?

PHP - spl_autoload 和命名空间 - 不适用于大写字母

PHP 限制表中的行数

php - DOMXpath查询返回null

javascript - 基于 JavaScript 中的另一个列表更新列表

javascript - Angular 上的嵌套 ng-repeat 不起作用