【问题标题】:How to parse JSON from a URL with PHP如何使用 PHP 从 URL 解析 JSON
【发布时间】:2015-08-12 11:59:35
【问题描述】:

我有这个网址:

http://server.com/api.php?results

{"Name":"Pit, Loka","Current":{"Item":"16","test":"test","test":"84","test":"ok"}}

我猜 PHP 示例是:

<?php
$file = file_get_contents("http://server.com/api.php?results=item");
$data = json_decode($file);
print_r($data);
?>

但我无法得到任何结果。
我该如何解决这个问题?

【问题讨论】:

  • 你能在浏览器上得到结果吗?
  • 检查您收到的错误。您要么没有获得内容,要么 json 解码失败。实施错误检查。
  • 尝试一些调试:尝试echo-ing $file 中的字符串,它是空的吗?你看到任何错误吗? (error_reporting(E_ALL))
  • 你试过var_dump() 吗?

标签: php json parsing


【解决方案1】:
<?php
$file = file_get_contents("http://server.com/api.php?results=item");
$data = json_decode($file);

$name = $data->Name; // "Name":"Pit, Loka"
$current = $data->Current->Item; //"Current":{"Item":"16","test":"test","test":"84","test":"ok"}

foreach ($current as $currentX) {
    echo $currentX->Item;
}
?>

它应该可以工作...请测试。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-01
    • 2019-08-11
    • 2015-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多