tags:

views:

2464

answers:

3

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?

+13  A: 

Typecast the SimpleXMLObject to a string:

$foo = array( (string) $xml->channel->item->title );

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.

Aron Rotteveel
That's cleaner than using a sprintf. I like it
Mark Biek
Note that using a function that accepts string arguments will automatically do this type casting (e.g. echo, str_replace, substr).
Ross
Thanks Aron, I thought a typecast was the way to do this but it just didnt feel right.Now that I know the _toString method is private it makes sense.
Neil Aitken
A: 

I agree with Aron. Type-casting using (string) will do the trick. I had the very same problem a few months ago.

May I suggest you use DOMDocument to read XML in PHP. SimpleXML is fun to start with, but you soon find its limits.

DOMDocument is what is used underneath SimpleXML.

Vincent
note that dom_import_simplexml() can be used, so DOM can conjunction with simpleXML.
null
+1  A: 

You can use the PHP function

strval();

This function returns the string values of the parameter passed to it.

Undefined
Unfortunately strval() doesn't work on arrays or objects.
Mark Biek