文字

DOMDocument::getElementsByTagName

(PHP 5, PHP 7)

DOMDocument::getElementsByTagNameSearches for all elements with given local tag name

说明

public DOMNodeList DOMDocument::getElementsByTagName ( string $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

参见

  • DOMDocument::getElementsByTagNameNS() - Searches for all elements with given tag name in specified namespace

用户评论:

[#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(./
?>

上一篇: 下一篇: