PHP, json_encode, json_decode SimpleXML object

The function in my application does the following:

  • Capturing a Web Page Using Snoopy
  • Upload result to DOMDocument
  • Loading a DOMDocument into a simple XML object
  • Run XPath to select the section of the required document.
  • json_encode result and save to database for later use.

My problem arises when restoring this block from the database and decrypting it. I can see @attributes when I have a var_dump object, but cannot find a combination of commands that allows me to access them.

Error message: Fatal error: you cannot use an object of type stdClass as an array

Below is a sample of my object. I tried, among others, what worked.

echo $obj['class']; stdClass Object ( [@attributes] => stdClass Object ( [class] => race_idx_hdr ) [img] => stdClass Object ( [@attributes] => stdClass Object ( [src] => /Images/Icons/i_blue_bullet.gif [alt] => image [title] => United Kingdom ) ) [a] => Fast Cards ) 
+4
source share
3 answers

When you decode 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-family syntax used by SimpleXMLElement objects to allow access to attributes.

Usually you should use the serialize () and unserialize () functions instead of json_encode / decode to store objects in the database, but unfortunately SimpleXMLElements do not work with them.

Alternatively, why not just save the actual xml and read it back to SimpleXML after retrieving 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); 
+2
source

Actually, I really don’t understand what you are trying to do, and where the error is being raised, but you can use to access the properties of your object

 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 strange syntax ( $obj->{'@attributes'} ) is required because the @ symbol is reserved in PHP and cannot be used for identifiers.

+3
source

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

 $asArray = (array)$myObj; echo $asArray['@attribute']; 
0
source

All Articles