嗨,我有以下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编辑/道歉
一个简单的解决方案是将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>';
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句