在php中访问json数组的元素

时间:2015-03-12 10:02:54

标签: php json

您好我有以下json:

{"@attributes":{"Version":"2.0"},"METADATA":{"FIELDS":{"FIELD":[{"@attributes":{"attrname":"street1","fieldtype":"string","width":"50"}},{"@attributes":{"attrname":"town","fieldtype":"string","width":"50"}},{"@attributes":{"attrname":"addresscode","fieldtype":"i4"}},{"@attributes":{"attrname":"personcode","fieldtype":"i4"}},{"@attributes":{"attrname":"Forename","fieldtype":"string","width":"15"}},{"@attributes":{"attrname":"Surname","fieldtype":"string","width":"20"}},{"@attributes":{"attrname":"Phone","fieldtype":"string","width":"30"}},{"@attributes":{"attrname":"Phone2","fieldtype":"string","width":"30"}}]},"PARAMS":{"@attributes":{"DEFAULT_ORDER":"1","PRIMARY_KEY":"1","LCID":"1033"}}},"ROWDATA":{"ROW":[{"@attributes":{"street1":"x House ","town":"town1","addresscode":"xxx","personcode":"yyy","Forename":"John","Surname":"Doe","Phone2":"087 123 4567"}},{"@attributes":{"street1":"street2 ","town":"town2","addresscode":"zzz","personcode":"ppp","Forename":"Jane","Surname":"Doe","Phone":"0831234567"}}]}}

我一直无法解析它,我收到了错误:

Parse error: syntax error, unexpected '@', expecting identifier (T_STRING) or variable (T_VARIABLE) or '{' or '$'

以下代码:

$filename = 'C:/myfile.xml'; 
$Users = simplexml_load_file($filename);
$JSON_Users = json_encode($Users);
$jfo = json_decode($JSON_Users);
$UsersParsed = $jfo->ROWDATA->ROW;

foreach ($UsersParsed as $user) {

    $FName = $user->@attributes->Forename;
    $SName = $user->@attributes->Surname;
    echo $FName.' and '.$SName.'<br>';

}

我在没有@符号的情况下尝试了并且出现了错误:

Notice: Undefined property: stdClass::$attributes

任何帮助表示赞赏

/ EDITED JSON /道歉

2 个答案:

答案 0 :(得分:2)

@是PHP中的保留运算符,不能是变量名的一部分。它抑制了标准错误输出。

要使用变量名中不允许的字符来处理对象属性,请使用{'name'}语法。

$FName = $user->{'@attributes'}->Forename;

注意:将SimpleXML与XPath或甚至DOM + XPath一起使用会更有效率。

答案 1 :(得分:1)

一个简单的解决方案是将TRUE作为第二个参数传递给json_decode()。这样它就会返回一个数组而不是一个对象,在你改变访问其内容的方式后,一切都顺利进行:

$filename = 'C:/myfile.xml'; 
$Users = simplexml_load_file($filename);
$JSON_Users = json_encode($Users);
$jfo = json_decode($JSON_Users, TRUE);
$UsersParsed = $jfo['ROWDATA']['ROW'];

foreach ($UsersParsed as $user) {

    $FName = $user['@attributes']['Forename'];
    $SName = $user['@attributes']['Surname'];
    echo $FName.' and '.$SName.'<br>';

}

另一个解决方案是使用correct syntax来访问对象的属性,因为它们包含变量名中不允许的字符(例如,因为它们是通过转换而不是使用常规方式创建的):

foreach ($UsersParsed as $user) {

    $FName = $user->{'@attributes'}->Forename;
    $SName = $user->{'@attributes'}->Surname;
    echo $FName.' and '.$SName.'<br>';

}