'Serialization of 'SimpleXMLElement' is not allowed when saving in Wordpress post_meta 'Serialization of 'SimpleXMLElement' is not allowed when saving in Wordpress post_meta wordpress wordpress

'Serialization of 'SimpleXMLElement' is not allowed when saving in Wordpress post_meta


(Nearly) everything returned when you are traversing a SimpleXML object is actually another SimpleXML object. This is what lets you write $item->OfferSummary->LowestNewPrice->Amount: requesting ->OfferSummary on the $item object returns an object representing the OfferSummary XML node, so you can request ->LowestNewPrice on that object, and so on. Note that this applies to attributes too - $someNode['someAttribute'] will be an object, not a string!

In order to get the string content of an element or attribute, you have to "cast" it, using the syntax (string)$variable. Sometimes, PHP will know you meant to do this, and do it for you - for instance when using echo - but in general, it's good practice to always cast to string manually so that you won't have any surprises if you change your code later. You can also cast to an integer using (int), or a float using (float).

The second part of your problem is that SimpleXML objects are stored rather specially in memory, and can't be "serialized" (i.e. turned into a string that completely describes the object). This means that if you try to save them into a database or session, you will get the error you're seeing. If you actually wanted to save a whole block of XML, you could use $foo->asXML().

So, in short:

  • use $link = (string)$item->DetailPageURL; to get a string rather than an object
  • use update_post_meta($post->ID, 'ItemXML', $item->asXML()); if you ever want to store the whole item