首页 > 解决方案 > 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';这样,如果页面实际加载,我可以轻松地放手。

标签: phpjson

解决方案


您的 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";

?>

推荐阅读