(PHP 4 >= 4.1.0)
DomElement->get_elements_by_tagname — Gets elements by tagname
Gets all the sub elements with the specific name within the current element.
The name of the seeked element.
Returns an array of DomElement objects.
Beispiel #1 Getting a content
<?php
if (!$dom = domxml_open_mem($xmlstr)) {
echo "Error while parsing the document\n";
exit;
}
$root = $dom->document_element();
$node_array = $root->get_elements_by_tagname('element');
foreach ($node_array as $node) {
echo ' - ' . $node->get_content() . "\n";
}
?>
This example uses get_elements_by_tagname() and child_nodes() to output the contents of the xml file. The sample xml file and php code are below.
<?xml version="1.0" encoding="iso-8859-1"?>
<dictionary>
<entry>
<word>Hello</word>
<meaning>used to express a greeting</meaning>
<example>Hello World!</example>
</entry>
</dictionary>
<?php
$xml_path = "/some/dir/dictionary.xml";
if (!$dom = domxml_open_file($xml_path)) {
//the above requires absolube path
exit("Could not access the XML source.");
}
$root = $dom->document_element(); //obtain the root
$array_entry = $root->get_elements_by_tagname("entry"); //gets all <entry> DomElems
foreach ($array_entry as $entry_dom_elem) {
$childnodes = $entry_dom_elem->child_nodes();
foreach ($childnodes as $child) { //cycle thru <word>, <meaning>, <example>
echo "node name: ".$child->tagname() . "; contains: " . $child->get_content()."<br>";
}
}
?>
The above code outputs:
node name: word; contains: Hello
node name: meaning; contains: used to express a greeting
node name: example; contains: Hello World!
Function get_elements_by_tagname() is only defined for the DocumentRoot-Element rather than for any DocumentElement.
if you want to search for tagnames with namespaces, do it the following way:
(it's a work around, not a really proper solution..)
$dom = domxml_open_mem($xmlval);
$ctx=xpath_new_context($dom);
$ctx->xpath_register_ns("yns","http://your.name.space/uri");
$nodes = $dom->get_elements_by_tagname("yns:tagname",$ctx);