用php读取json结果时出错

时间:2017-05-17 09:27:57

标签: php json

我试着读这个json结果:

stdClass Object (
    [search-results] => stdClass Object
        (
            [opensearch:totalResults] => 1770323
            [opensearch:startIndex] => 0
            [opensearch:itemsPerPage] => 25
            [opensearch:Query] => stdClass Object
                (
                    [@role] => request
                    [@searchTerms] => gene
                    [@startPage] => 0
                )
            [link] => Array
                (
                    [0] => stdClass Object
                        (
                            [@_fa] => true
                            [@href] => http://api.els.com/content/search/scidir?start=0&count=25&query=gene
                            [@ref] => self
                            [@type] => application/json
                        )
                )
        )
    )

我的代码:

$json = file_get_contents($requete); // dans la variable json
$obj = json_decode($json);
echo $obj->search-results->link[0]; // (I tried also  : $obj->{'search-results'}->link[0];

代码错误:

  

解析错误:语法错误,意外' - >' (T_OBJECT_OPERATOR),   期待','或';'在

我不明白我的错在哪里,拜托,请你有个主意吗? 谢谢 让

2 个答案:

答案 0 :(得分:0)

  

有效的变量名称以字母或下划线开头,后跟   任意数量的字母,数字或下划线。作为一个常规   表达,它将表达如下:   ' [A-ZA-Z_ \ x7f- \ XFF] [A-ZA-Z0-9_ \ x7f- \ XFF] *'

Check here

您使用$obj->search-results->link[0];。我认为搜索结果有问题会将json中的-更改为_(下划线)并再次检查。

答案 1 :(得分:0)

如果search-result是固定对象,那么您可以尝试:

$search = 'search-results'; //declare variable 
echo $obj->{$search}->link[0]; // (I tried also  : $obj->{'search-results'}->link[0];
相关问题