【问题标题】:JSON to PHP Array using file_get_contents not working使用 file_get_contents 的 JSON 到 PHP 数组不起作用
【发布时间】:2016-05-11 15:22:20
【问题描述】:

我正在尝试从 dailymotion 获取视频网址。 我得到了 JSON 结果,并通过在线工具对其进行了有效测试,但是当我使用 js_decode 和 print_r 时,它会显示类似警告

<?php

$content = file_get_contents("http://www.dailymotion.com/embed/video/x49oyt5");

$content = explode(',"qualities":', $content);

$json = explode(',"reporting":', $content[1]);

$json = $json[0];

$mycontent = file_get_contents($json);

$response = json_decode($mycontent, true);

print_r($response);

?>

我想从 JSON 中获取视频质量和视频 url。

【问题讨论】:

  • explode 之后检查您的$json 格式是否正确?其次,你为什么用了两次file_get_contents
  • 尝试获得$content 一次,只需json_decode($content, true); 你将获得array 然后你就可以玩了。我认为两次使用file_get_contents 不是一个好方法。
  • 谢谢它的工作。如何读取 json 值?
  • 循环遍历结果数组,例如$array = json_decode($json,true);foreach ($array as $key=&gt;$value){ echo $key.'---'; print_r($value[0]['url']); echo '&lt;br&gt;'; }

标签: php json file-get-contents


【解决方案1】:

您正在对实际上已经是 JSON 的内容使用 file_get_contents。

更新代码,测试;)

<?php

$content = file_get_contents("http://www.dailymotion.com/embed/video/x49oyt5");

$content = explode(',"qualities":', $content);

$json = explode(',"reporting":', $content[1]);

$json = $json[0];

$videos = json_decode($json,true);

//Cycle through the 1080 videos and print the video urls
foreach($videos[1080] as $video){
  printf("Video type:%s URL:%s\n", $video['type'], $video['url']);
}

//Cycle through the 720 videos and print the video urls
foreach($videos[720] as $video){
  printf("Video type:%s URL:%s\n", $video['type'], $video['url']);
}
?>

【讨论】:

  • 谢谢,这是个大错误。那么如何读取 240、380、480 和 url 值等属性值?
  • 资源按质量分组,因此您只需访问所需的质量密钥并循环浏览资源
  • 你能写一些工作代码来访问属性吗?谢谢
【解决方案2】:

使用array_keys($array),您可以从数组中获取所有键,它将返回一个包含键的数组。

<?php

$content = file_get_contents("http://www.dailymotion.com/embed/video/x49oyt5");

$content = explode(',"qualities":', $content);

$json = explode(',"reporting":', $content[1]);

$json = $json[0];

$mycontent = file_get_contents($json);

$response = json_decode($mycontent, true);

$qualities = array_keys($response)

print_r($qualities);

?>

【讨论】:

    猜你喜欢
    • 2020-03-27
    • 2012-03-20
    • 2012-08-30
    • 2013-06-30
    • 1970-01-01
    • 1970-01-01
    • 2015-12-09
    • 2015-12-21
    • 2021-08-12
    相关资源
    最近更新 更多