note 80576 added to ref.simplexml
| From: | mtudor at N0SPMicefusion dot co dot uk | Date: | Wed, 23 Jan 2008 11:50:29 +0000 |
| Subject: | note 80576 added to ref.simplexml | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-135328@lists.php.net to get a copy of this message | ||
Be careful when trying to access a repeated xml tag such as in the example below:
<?php
$xmlText = "<test>
<group>
<multi>One</multi>
<multi>Two</multi>
</group>
</test>";
$xml = new SimpleXMLElement($xmlText);
?>
SimpleXML will convert this into an object as follows:
SimpleXMLElement Object
(
[group] => SimpleXMLElement Object
(
[multi] => Array
(
[0] => One
[1] => Two
)
)
)
From this, you may think as I did, that the following snippet will yield an Array with two elements:
<?php
print_r($xml->group->multi)
?>
What actually happens is that SimpleXMLElement assumes that you want the first element in the array,
so the above snippet will actually return:
SimpleXMLElement Object
(
[0] => One
)
Accessing using Array notation:
<?php
print_r($xml->group->multi[1]);
?>
Will return:
SimpleXMLElement Object
(
[0] => Two
)
as would be expected. It seems that SimpleXML has a mechanism to determine whether or not you are
using Array notation and if not, returning the first element of the array.
Unfortunately, this is a real problem for using functions such as count() and is_array().
is_array($xml->group->multi) will actually return false, as you are actually testing against
the first element of the multi array, wrapped in a SimpleXMLElement object.
The solution, it would seem, is one of the following:
1. Access the element using xpath, which returns an array that can be counted and edited etc.:
<?php
print_r($xml->group->xpath("multi"));
?>
2. Use isset to detect if array index 1 is present:
<?php
if(isset($xml->group->multi[1]))
{
echo "The XML has more than one multi element";
}
?>
See http://vega.rd.no/article/simplexml-not-that-simple
for further information.
I wonder if it might be worth including this in the body of the documentation, as it is quite a big
gotcha?
----
Server IP: 194.145.210.3
Probable Submitter: 90.152.49.58
----
Manual Page -- http://www.php.net/manual/en/ref.simplexml.php
Edit -- https://master.php.net/note/edit/80576
Del: integrated -- https://master.php.net/note/delete/80576/integrated
Del: useless -- https://master.php.net/note/delete/80576/useless
Del: bad code -- https://master.php.net/note/delete/80576/bad+code
Del: spam -- https://master.php.net/note/delete/80576/spam
Del: non-english -- https://master.php.net/note/delete/80576/non-english
Del: in docs -- https://master.php.net/note/delete/80576/in+docs
Del: other reasons-- https://master.php.net/note/delete/80576
Reject -- https://master.php.net/note/reject/80576
Search -- https://master.php.net/manage/user-notes.php