正在将JSON文件导入PHP[error正在尝试获取非对象的属性]


Importing JSON file to PHP [error Trying to get property of non-object]

我尝试将一个JSON文件导入PHP并使用它,但服务器返回:"正在尝试获取非对象的属性"。如果我手动将JSON文件中的文本放入PHP文件,服务器将正确返回

index.php

<?php
    if (isset($_GET['dir'])) {
        $dir = $_GET['dir'];
        $dir = $dir . "/";
    } else {
        $dir = "";
    }
    $about_dir = $dir . "about.json";

    //1st try
    $json_data = file_get_contents($about_dir);
    $json_a = json_decode($json_data, true);
    echo $json_a['T'];
    //2nd try
    $json = json_decode($json_data, true);
    print $json->{"T"};
    //3th try
    $json = '{"T": "Test","About": "About T"}';
    $obj = json_decode($json);
    print $obj->{'About'};
    return $about_dir;
?>

关于.json

[
    {
    "T": "Test",
    "About": "About T"
    }
]

怎么了?我试着效仿这个例子(http://php.net/manual/en/function.json-encode.php(。此外,我在stackoverflow中搜索过这里,但从未使用JSON。有人能帮我吗?非常感谢。

您必须使用箭头访问对象元素,使用方括号访问数组元素。这是一个数组,所以你必须在这里使用方括号。

我使用类似的方法将JSON转换为PHP

function json2object($json){ 
  $json_array = json_decode($json, true); 
  foreach($json_array as $k=>$v){ 
    $this->{$k}=$v;
  } 
}

所以在你的情况下,你可以使用这样的东西:

  $json_a = json_decode($json_data, true); 
  foreach($json_a as $k=>$v){ 
    $obj->{$k}=$v;
  } 

希望这对你和我一样有效。

 $json = '[
     {
    "T": "Test",
    "About": "About T"
    }
]';
    $obj = json_decode($json);
    //print $obj->{'About'};
    //print_r($obj);
    foreach($obj as $value)
    {
        echo $value->T;
        echo $value->About;
    }

我尝试了一下,但错误似乎在get_contents中。

如果我使用这个代码:

$json = '{"T": "Test","About": "About T"}';
$obj = json_decode($json);    
var_dump(json_decode($json));

返回为:

About T object(stdClass)#3 (2) { ["T"]=> string(4) "Test" ["About"]=> string(7) "About T" } 

如果我导入内容:

$json = file_get_contents($about_dir);
//$json = '{"T": "Test","About": "About T"}';
$obj = json_decode($json);
var_dump(json_decode($json));

并在about.json中写下这行:{"T":"Test","about":"about T"}

返回为:

NULL