PHP, json_encode, json_decode of SimpleXML Object

吃可爱长大的小学妹 提交于 2019-12-01 19:01:09

When you decode the json from the database, you get an object of type 'stdClass' instead of the original type 'SimpleXMLElement' returned by the SimpleXMLElement::xpath function.

The stdClass object does not 'know' about the pseudo array syntax used by SimpleXMLElement objects to allow accessing the attributes.

Normally you would use the serialize() and unserialize() functions instead of json_encode/decode to store objects in a database, but unfortunately, SimpleXMLElements are not working with those.

As an alternative, why not just store the actual xml and read it back to SimpleXML after fetching it from the database:

// convert SimpleXMLElement back to plain xml string
$xml = $simpleXML->asXML();

// ... code to store $xml in the database
// ... code to retrieve $xml from database

// recreate SimpleXMLELement
$simpleXML = simplexml_load_string($xml);

I actually don't really understand what you're trying to do and where the error is thrown, but to access the properties of your object you can use

echo $obj->{'@attributes'}->class; // prints "race_idx_hdr"
echo $obj->img->{'@attributes'}->src; // prints "/Images/Icons/i_blue_bullet.gif"
echo $obj->img->{'@attributes'}->alt; // prints "image"
echo $obj->img->{'@attributes'}->title; // prints "United Kingdom"
echo $obj->a; // prints "Fast Cards"

This weird syntax ($obj->{'@attributes'}) is required because the @-symbol is reserved in PHP and cannot be used for identifiers.

If an object is converted to an array, the result is an array whose elements are the object's properties.

$asArray = (array)$myObj;
echo $asArray['@attribute'];
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!