php - Json_decode 未正确显示
问题描述
嗨,我整天都在努力解决这个问题。
出于某种原因,如果我远程加载 JSON,它会使用以下内容正确解码;
$uri = 'http://example.com/json
$data = file_get_contents($uri);
$json = json_decode($data);
但是如果我确实尝试从变量加载 json 它不起作用 print_r() 什么也没给我,我试过了;
$attch = '{"url": "https://example.com/messages/AgEFFo5ZtHR8rorLtJhMdpu9FKM_X11wZA==/attachments/0", "content-type": "application/pdf", "name": "20201181000954.pdf", "size": 18419}';
$jsn = json_decode($attch, true);
$url = $jsn[0]->url;
$size = $jsn[0]->size;
$name = $jsn[0]->name;
$content_type = $jsn[0]->content-type;
print($url);
print_r($size);
print_r($name);
echo 'testing';
和
$attch = '{"url": "https://example.com/messages/AgEFFo5ZtHR8rorLtJhMdpu9FKM_X11wZA==/attachments/0", "content-type": "application/pdf", "name": "20201181000954.pdf", "size": 18419}';
$jsn = json_decode($attch, true);
$url = $jsn->url;
$size = $jsn->size;
$name = $jsn->name;
$content_type = $jsn->content-type;
print_r($url);
print_r($size);
print_r($name);
echo 'testing';
我只有 echo 'testing';
这样,如果页面实际加载,我可以轻松地放手。
解决方案
您的 json 正在获取不在对象中的数组格式。您不能作为对象访问。
的输出
var_dump($jsn);
print_r($jsn);
array(4) {
["url"]=>
string(79) "https://example.com/messages/AgEFFo5ZtHR8rorLtJhMdpu9FKM_X11wZA==/attachments/0"
["content-type"]=>
string(15) "application/pdf"
["name"]=>
string(18) "20201181000954.pdf"
["size"]=>
int(18419)
}
Array
(
[url] => https://example.com/messages/AgEFFo5ZtHR8rorLtJhMdpu9FKM_X11wZA==/attachments/0
[content-type] => application/pdf
[name] => 20201181000954.pdf
[size] => 18419
)
您必须使用
$jsn['url'];
代码:
<?php
// Your code here!
$attch = '{"url": "https://example.com/messages/AgEFFo5ZtHR8rorLtJhMdpu9FKM_X11wZA==/attachments/0", "content-type": "application/pdf", "name": "20201181000954.pdf", "size": 18419}';
$jsn = json_decode($attch, true);
//var_dump($jsn);
print_r($jsn);
$url = $jsn["url"];
$size = $jsn["size"];
$name = $jsn["name"];
$content_type = $jsn["content-type"];
echo $url."\n";
echo $size."\n";
echo $name."\n";
echo $content_type."\n";
?>
推荐阅读
- reactjs - 如何在反应中从 URL 中提取查询参数?
- windows - 当我不交互时,Windows CMD/Power Shell 休眠
- java - 当我通过类(而不是接口)查找由 JDK 动态代理包装的 bean 时,为什么我没有遇到任何异常?
- python - 我可以使用 statsmodel ARIMA 插入时间序列吗?
- validation - 如何手动检查 CakePHP 模型字段要求?
- python - python re.findall 返回一个元组列表(需要字符串)
- css - 使用 if() css 函数将大小与单位进行比较
- dataframe - Databricks - FileNotFoundException
- javascript - 如何在 JavaScript 中获取 var 的一部分?
- c++ - 如何将 xvalue 的 std::move 执行到 void* ptr 中?