解码JSON和php.适用于变量,而不是URL

pan*_*uli 1 php json

我是php的json解码新手.这是我的情况.我需要抓取一个非常简单的json调用并在我的HTML页面上解析它.这是json的内容:

[{"id":"793","date":"Apr. 18, 2011","title":"the cat in the hat","url":"http:\/\/www.somesite.com\/community\/blogs\/id-793"},{"id":"788","date":"Apr. 12, 2011","title":"the fox has sox","url":"http:\/\/www.somesite.com\/community\/blogs\/id-788"}]
Run Code Online (Sandbox Code Playgroud)

等等...

当我继续把它放在我的php文件中的字符串中时:

$json = [{...}]
$arr = json_decode($json,true);
foreach($arr as $item) {
    echo "title: ". $item['title'] ."<br>"; 
}
Run Code Online (Sandbox Code Playgroud)

我打印出的标题没有问题.相反,如果我说:

$arr = json_decode("url_path_here",true);
foreach($arr as $item) {
    echo "title: ". $item['title'] ."<br>"; 
}
Run Code Online (Sandbox Code Playgroud)

我收到一个错误,"为foreach()提供的参数无效",数组只是空的.

如果这很重要,那么在开发期间,Feed将位于不同的服务器上.我只是不确定我在这里做错了什么.我正在使用PHP 5.

谢谢!

cee*_*yoz 8

json_decode 采用字符串,而不是URL.

这可能会奏效:

$arr = json_decode(file_get_contents("url_path_here"),true);
foreach($arr as $item) {
    echo "title: ". $item['title'] ."<br>"; 
}
Run Code Online (Sandbox Code Playgroud)

  • 需要注意的是:有时PHP不会被设置为允许文件功能中的URL.如果是这种情况,您可能需要使用curl. (3认同)