Workaround: SimpleXML Problem with Single Element Values
Tuesday, October 24, 2006
Quinn and I are working on a project that involves parsing a large number of XML transactions in PHP. We chose to use SimpleXML because it’s lightweight and the XML we are parsing isn’t really complicated enough to warrant using the full Dom.
We’ve run into a lot of strange issues with SimpleXML, most notablly that it always seems to return an array even if you query for a single element. We’ve also uncovered some inconsistent errors that seem to occur when trying to get the element value.
Here’s the sample XML that we are using. (ok, it’s not the real thing, I changed all the names)
<?xml version=”1.0″?>
<article username=”johnny”>
<thepost>
<bgcolor>#6699cc</bgcolor>
<commentcount>50</commentcount>
<text>The article text goes here</text>
</thepost>
</article>
First, we read the contents of the XML from a file named test.xml into a variable like so:
$obj = simplexml_load_string(file_get_contents(”test.xml”));
If we were to do a print_r() on the $obj variable, we’d see this output:
SimpleXMLElement Object ( [@attributes] => Array ( [username] => johnny ) [thepost] => SimpleXMLElement Object ( [bgcolor] => #6699cc [commentcount] => 50 [text] => The article text goes here ) )
So then we did a print_r() on the $obj->commentcount child item, and here’s the weirdness that ensued:
SimpleXMLElement Object ( [0] => 50 )
When we tried to access the item using $obj->commentcount[0] it would return nothing every time. It worked just fine for the bgcolor element, but wouldn’t work for the commentcount. We started thinking that it must be something to do with the integer in the field instead.
Finally Quinn stumbled on a method that worked:
echo(1 * $obj->commentcount[0]);
We then figured out that you could also use this syntax, which would also work:
$cc = $obj->commentcount[0];
echo($cc);
What seems to be going on is that the object can’t be echoed out to a string directly without “casting” it first.
So, the moral of this story is that you may want to pull SimpleXML child elements out into seperate variables if you are having issues returning the values. What a pain.
November 23rd, 2008 at 9:39 pm
Well, thank you very much! You really did a good job! Thank you!