©
Dieses Dokument verwendet PHP-Handbuch für chinesische Websites Freigeben
(PHP 5, PHP 7)
DOMDocument::getElementsByTagName — Searches for all elements with given local tag name
$name
)This function returns a new instance of class DOMNodeList containing all the elements with a given local tag name.
name
The local name (without namespace) of the tag to match on. The special value * matches all tags.
A new DOMNodeList object containing all the matched elements.
Example #1 Basic Usage Example
<?php
$xml = <<< XML
<?xml version="1.0" encoding="utf-8"?>
<books>
<book>Patterns of Enterprise Application Architecture</book>
<book>Design Patterns: Elements of Reusable Software Design</book>
<book>Clean Code</book>
</books>
XML;
$dom = new DOMDocument ;
$dom -> loadXML ( $xml );
$books = $dom -> getElementsByTagName ( 'book' );
foreach ( $books as $book ) {
echo $book -> nodeValue , PHP_EOL ;
}
?>
以上例程会输出:
Patterns of Enterprise Application Architecture Design Patterns: Elements of Reusable Software Design Clean Code
[#1] rsvvuuren at hotmail dot com [2014-01-10 10:00:14]
I was in need of $dom->getElementsByTagName that would hist magic within a contextNode.
Why i needed getElementsByTagName instead of just simple using an xPath->query is because while looping through the returned nodelist, more nodes with the tagName i was looking for where created.
When using getElementsByTagName, the new nodes are "added" to the nodelist i already am looping through.
When using an xpath query, you wil only loop through the original nodelist, the newly created elements wil not appear in that nodelist.
I was already using an extended class on domDocument, so it was simple to create an kind of getElementsByTagName that would accept an contextNode.
<?php
class SmartDocument extends DOMDocument {
private $localDom;
public $xpath;
private $serialize = array('localDom');
private $elemName;
private $elemCounter;
function __construct() {
parent::__construct ( '1.0', 'UTF-8' );
$this->preserveWhiteSpace = false;
$this->recover = TRUE;
$this->xpath = new DOMXpath ( $this );
}
public function getElementsByTagNameContext($name, $contextNode) {
if($this->elemName!=$name) {
$this->elemCounter = 0;
$this->elemName =$name;
}
$this->elemLength = $this->xpath->evaluate('count(./
?>