[英]how to convert this json data in php
我正在使用一个 api,它给了我一个非常奇怪的 json 格式..我正在发布它的数据,我正在通过它..
info = { "title" : "Asian Dad: B Again!? (you die)", "image" : "http://i.ytimg.com/vi/IN7o2Iy89WQ/default.jpg", "length" : "2", "status" : "serving", "progress_speed" : "", "progress" : "", "ads" : "", "pf" : "", "h" : "f53762dab34022e9d851ab71e0bf166f" };
我正在尝试在 php 中打印这些数据,但我无法做到这一点..我的网页上没有显示任何内容,..我的代码是..
首先我试过,
<?php
$url="http://www.website-name.com/a/itemInfo/?video_id=IN7o2Iy89WQ&ac=www";
$info=file_get_contents($url);
$info=json_decode($info,true);
echo $info;
?>
我的第二次尝试是,
<?php
$url="http://www.website-name.com/a/itemInfo/?video_id=IN7o2Iy89WQ&ac=www";
$info=file_get_contents($url);
$info=json_decode($info,true);
$info->h;
?>
我最后一次尝试是,
<?php
$url="http://www.website-name.com/a/itemInfo/?video_id=IN7o2Iy89WQ&ac=www";
$info=file_get_contents($url);
$info=json_decode($info,true);
$info['h'];
?>
什么都没有发生。。
请有人帮助我
API 网址转换...
该页面正在发送"info = { "title" : "Asian Dad: B Again!? (you die)", "image" : "http://i.ytimg.com/vi/IN7o2Iy89WQ/default.jpg", "length" : "2", "status" : "serving", "progress_speed" : "", "progress" : "", "ads" : "", "pf" : "", "h" : "058ce93db26fce4a9f1cb41ae2e7c1bb" };"
"info = { "title" : "Asian Dad: B Again!? (you die)", "image" : "http://i.ytimg.com/vi/IN7o2Iy89WQ/default.jpg", "length" : "2", "status" : "serving", "progress_speed" : "", "progress" : "", "ads" : "", "pf" : "", "h" : "058ce93db26fce4a9f1cb41ae2e7c1bb" };"
您不能对此使用 json_decode,因为info =
和;
最后不是json。 你必须去掉info =
和;
.
$url="http://www.website-name.com/a/itemInfo/?video_id=IN7o2Iy89WQ&ac=www";
$info = file_get_contents($url);
$info = trim($info, "info = ");
$info = rtrim($info, ";");
$json = json_decode($info, true);
echo $json['status'];
我从您示例中的 URL 获得的数据是
info = { "title" : "Asian Dad: B Again!? (you die)", "image" : "http://i.ytimg.com/vi/IN7o2Iy89WQ/default.jpg", "length" : "2", "status" : "serving", "progress_speed" : "", "progress" : "", "ads" : "", "pf" : "", "h" : "5cddd4d1667f24aa9a0f5a6cc21e24e3" };
这是一个可执行的 JavaScript 片段,实际上不是 JSON。 您的 php 失败的原因是由于 'info =' 部分... json_encode 在解码失败时返回 null。
虽然这是将变量分配给 JavaScript 对象,但如果您删除了 'info =' 和分号,它也可以作为 JSON 工作。 假设响应是可预测的,您可以使用 php str_replace 来执行此操作,但是找到一个为您的源返回 JSON 的 API 将是一个更可靠和干净的解决方案。
如果您在注释中提到的第二行var_dump($info)
上获得NULL
,则file_get_contents()
不会检索数据。
这很可能是因为 PHP.ini 中的allow_url_fopen
设置为 false
获取 JSON 编码的字符串并将其转换为 PHP 变量。
如果第二个参数设置为 true,则返回一个数组!
所以你的第一次和第二次尝试是错误的。! 它应该第三次尝试。 只需检查您是否检索了数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.