When working with SimpleXML objects, it's sometimes necessary to convert an object to a string, regardless of the context. Consider the following XML:
<channel> <item> <title>This is title 1</title> </item> </channel>
The following code successfully retrieves the title as a string:
$xml = simplexml_load_string($xmlstring); echo $xml->channel->item->title;
However, if you attempt to store the title in an array, it remains a SimpleXML object:
$foo = array( $xml->channel->item->title );
To avoid this issue, you can use one of the following methods:
The simplest solution is to typecast the SimpleXMLObject to a string:
$foo = array( (string) $xml->channel->item->title );
This code calls the __toString() method on the SimpleXMLObject, which converts it to a string. While this method is not publicly available, it can be invoked using this technique.
The above is the detailed content of How Do I Convert a SimpleXML Object to a String in PHP?. For more information, please follow other related articles on the PHP Chinese website!