Let's say I have some XML like this
<channel>
<item>
<title>This is title 1</title>
</item>
</channel>
The code below does what I want in that it outputs the title as a string
$xml = simplexml_load_string($xmlstring);
echo $xml->channel->item->title;
Here's my problem. The code below doesn't treat the title as a string in that context so I end up with a SimpleXML object in the array instead of a string.
$foo = array( $xml->channel->item->title );
I've been working around it like this
$foo = array( sprintf("%s",$xml->channel->item->title) );
but that seems ugly.
What's the best way to force a SimpleXML object to a string, regardless of context?
The accepted answer actually returns an array containing a string, which isn't exactly what OP requested (a string). To expand on that answer, use:
Which returns the single element of the array, a string.
Another ugly way to do it:
It works, but it's not pretty.
There is native SimpleXML method SimpleXMLElement::asXML Depending on parameter it writes SimpleXMLElement to xml 1.0 file, Yes
You can use the PHP function
This function returns the string values of the parameter passed to it.
To get XML data into a php array you do this:
To get a childs child then just do this:
You can expand $xml-> through each level until you get what you want You can also put all the nodes into one array without the levels or just about any other way you want it.
Typecast the SimpleXMLObject to a string:
The above code internally calls
__toString()
on the SimpleXMLObject. This method is not publicly available, as it interferes with the mapping scheme of the SimpleXMLObject, but it can still be invoked in the above manner.