PHP : Function Reference : DOM Functions : DOMDocument->getElementsByTagName()
Examples ( Source code ) » DOMDocument->getElementsByTagName()
<?php
$xml =<<<EOT
<?xml version="1.0"?>
<config>
<section id="section1">
<param name="param1">value1</param>
<param name="param2">value2</param>
</section>
<section id="section2">
<param name="param3">value3</param>
</section>
</config>
EOT;
$dom = new DomDocument;
$dom->preserveWhiteSpace = FALSE;
$dom->loadXML($xml);
$params = $dom->getElementsByTagName('param');
foreach ($params as $param) {
echo $param -> getAttribute('name').'
';
}
?>
Expected result:
--------------
param1
param2
param3
finding values of a node
I don't know if this is that obvious but it was not for me, so in addition to gem at rellim dot com's posting:
adding
<?php
echo $param -> nodeValue.' ';
?>
to the loop will output
value1
value2
value3
gem
Here is an example of getElementsByTagName():
<?php
$xml =<<<EOT
<?xml version="1.0"?>
<config>
<section id="section1">
<param name="param1">value1</param>
<param name="param2">value2</param>
</section>
<section id="section2">
<param name="param3">value3</param>
</section>
</config>
EOT;
$dom = new DomDocument;
$dom->preserveWhiteSpace = FALSE;
$dom->loadXML($xml);
$params = $dom->getElementsByTagName('param');
foreach ($params as $param) {
echo $param -> getAttribute('name').' ';
}
?>
Expected result:
--------------
param1
param2
param3
francois hill
Careful : getElementsByTagName will yield all elements with the given tag name under the present node, at any sub-level (i.e. among child nodes and all other descendant nodes)
|