在 PHP 中访问 JSON 数组的元素


accessing elements of json array in php

嗨,我有以下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

任何帮助表示赞赏

/编辑的JSON/道歉

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

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

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

注意:将 SimpleXML 与 XPath 甚至 DOM+XPath 结合使用会更有效率。

一个简单的

解决方案是将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>';
}

另一种解决方案是,当对象包含变量名称中不允许的字符时,使用正确的语法访问对象的属性(因为,例如,它们是通过转换创建的,而不是使用常规方式):

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