|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2008-12-05 14:29 UTC] maras3000 at gmail dot com
Description:
------------
When looking for list of values of a certain attribute in xml via xpath() method, the returned SimpleXMLElement object's attributes() method does not properly return array of attributes.
Reproduce code:
---------------
test.xml:
<?xml version="1.0"?>
<test>
<sth attr="1" />
<sth attr="2" />
<sth attr="3" />
</test>
index.php:
<pre>
<?php
$xml = simplexml_load_file('./test.xml');
$result = $xml->xpath('//@attr');
foreach($result as $node)
{
var_dump($node);
foreach($node->attributes() as $attribute => $value)
echo $atribute . " = " . (string)$value . "\n";
echo "---\n";
}
?>
</pre>
Expected result:
----------------
object(SimpleXMLElement)#2 (1) {
["@attributes"]=>
array(1) {
["attr"]=>
string(1) "1"
}
}
attr = 1
---
object(SimpleXMLElement)#3 (1) {
["@attributes"]=>
array(1) {
["attr"]=>
string(1) "2"
}
}
attr = 2
---
object(SimpleXMLElement)#4 (1) {
["@attributes"]=>
array(1) {
["attr"]=>
string(1) "3"
}
}
attr = 3
---
Actual result:
--------------
object(SimpleXMLElement)#2 (1) {
["@attributes"]=>
array(1) {
["attr"]=>
string(1) "1"
}
}
---
object(SimpleXMLElement)#3 (1) {
["@attributes"]=>
array(1) {
["attr"]=>
string(1) "2"
}
}
---
object(SimpleXMLElement)#4 (1) {
["@attributes"]=>
array(1) {
["attr"]=>
string(1) "3"
}
}
---
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Wed Oct 29 16:00:01 2025 UTC |
I think there are two errors in this reproduce code. First, there's a typo in the innermost foreach, $atribute instead of $attribute. Secondly, that XPath expression selects attributes (which explains why attributes() returns NULL, as attributes cannot have attributes), whereas it should select nodes. This code works as expected: Reproduce code: --------------- $xml = simplexml_load_file('./test.xml'); foreach ($xml->xpath('//*[@attr]') as $node) { foreach($node->attributes() as $attribute => $value) echo $attribute . " = " . (string)$value . "\n"; }