« The “Gtk-CRITICAL gtk_text_buffer_emit_insert assertion” warning in PHP-GTK2 | Home | 12 things you need to know about PHP »
DOMNodeList as an Array
By admin | August 31, 2008
When using getElementsByTagName, it returns a DOMNodeList which you can use with foreach, but you can’t use array indexes to access elements.
For example, you can use the following code to the contents of the first “test” tag:
<?php
$file = 'z.xml';
$xmlfile = new DOMDocument();
@$xmlfile->load($file);
$iplist = $xmlfile->getElementsByTagName('test');
$i = 0;
foreach($iplist as $v) {
if($i == 0) {
var_dump($v->nodeValue);
}
$i++;
}
?>
Use this as z.xml:
<?xml version="1.0" ?><test>Testing: hello, world</test>
So as you can see, the $iplist variable is acting like an array (via foreach behaviour). But try this code:
<?php
$file = 'z.xml';
$xmlfile = new DOMDocument();
@$xmlfile->load($file);
$iplist = $xmlfile->getElementsByTagName('test');
var_dump($iplist[0]->nodeValue);
?>
The error “Fatal error: Cannot use object of type DOMNodeList as array in /usr/dev/php5/error.php on line 6” should occur. To fix this, use $iplist->item(0) instead of $iplist[0], though you can still use DOMNodeList with foreach. The following code should work:
<?php
$file = 'z.xml';
$xmlfile = new DOMDocument();
@$xmlfile->load($file);
$iplist = $xmlfile->getElementsByTagName('test');
var_dump($iplist->item(0)->nodeValue);
?>
If you found this article helpful or useful, please help Compdigitec by spreading the word or by leaving a comment. Don’t forget to subscribe to Compdigitec Labs for more interesting articles!
If you found this article helpful or interesting, please help Compdigitec spread the word. Don’t forget to subscribe to Compdigitec Labs for more useful and interesting articles!
Topics: PHP | 6 Comments »
April 1st, 2012 at 20:10
Thank u. That’s what I needed
August 10th, 2012 at 17:13
Thank you very much.
November 9th, 2024 at 21:29
… [Trackback]
[…] Find More on on that Topic: compdigitec.com/labs/2008/08/31/domnodelist-as-an-array/ […]
November 12th, 2024 at 14:22
… [Trackback]
[…] Info on that Topic: compdigitec.com/labs/2008/08/31/domnodelist-as-an-array/ […]
November 16th, 2024 at 15:20
… [Trackback]
[…] Here you will find 24257 more Info to that Topic: compdigitec.com/labs/2008/08/31/domnodelist-as-an-array/ […]
November 22nd, 2024 at 13:18
… [Trackback]
[…] Find More Info here to that Topic: compdigitec.com/labs/2008/08/31/domnodelist-as-an-array/ […]