略微加速

PHP官方手册 - 互联网笔记

PHP - Manual: DOMElement

2024-03-29

The DOMElement class

(PHP 5, PHP 7, PHP 8)

类摘要

class DOMElement extends DOMNode implements DOMParentNode, DOMChildNode {
/* 属性 */
public readonly string $tagName;
public readonly mixed $schemaTypeInfo = null;
public readonly ?DOMElement $firstElementChild;
public readonly ?DOMElement $lastElementChild;
public readonly int $childElementCount;
/* 继承的属性 */
public readonly string $nodeName;
public ?string $nodeValue;
public readonly int $nodeType;
public readonly ?DOMNode $parentNode;
public readonly DOMNodeList $childNodes;
public readonly ?DOMNode $firstChild;
public readonly ?DOMNode $lastChild;
public readonly ?DOMNode $previousSibling;
public readonly ?DOMNode $nextSibling;
public readonly ?DOMNamedNodeMap $attributes;
public readonly ?DOMDocument $ownerDocument;
public readonly ?string $namespaceURI;
public string $prefix;
public readonly ?string $localName;
public readonly ?string $baseURI;
public string $textContent;
/* 方法 */
public __construct(string $qualifiedName, ?string $value = null, string $namespace = "")
public getAttribute(string $qualifiedName): string
public getAttributeNode(string $qualifiedName): DOMAttr|DOMNameSpaceNode|false
public getAttributeNodeNS(?string $namespace, string $localName): DOMAttr|DOMNameSpaceNode|null
public getAttributeNS(?string $namespace, string $localName): string
public getElementsByTagName(string $qualifiedName): DOMNodeList
public getElementsByTagNameNS(?string $namespace, string $localName): DOMNodeList
public hasAttribute(string $qualifiedName): bool
public hasAttributeNS(?string $namespace, string $localName): bool
public removeAttribute(string $qualifiedName): bool
public removeAttributeNode(DOMAttr $attr): DOMAttr|false
public removeAttributeNS(?string $namespace, string $localName): void
public setAttribute(string $qualifiedName, string $value): DOMAttr|bool
public setAttributeNode(DOMAttr $attr): DOMAttr|null|false
public setAttributeNodeNS(DOMAttr $attr): DOMAttr|null|false
public setAttributeNS(?string $namespace, string $qualifiedName, string $value): void
public setIdAttribute(string $qualifiedName, bool $isId): void
public setIdAttributeNode(DOMAttr $attr, bool $isId): void
public setIdAttributeNS(string $namespace, string $qualifiedName, bool $isId): void
/* 继承的方法 */
public DOMNode::appendChild(DOMNode $node): DOMNode|false
public DOMNode::C14N(
    bool $exclusive = false,
    bool $withComments = false,
    ?array $xpath = null,
    ?array $nsPrefixes = null
): string|false
public DOMNode::C14NFile(
    string $uri,
    bool $exclusive = false,
    bool $withComments = false,
    ?array $xpath = null,
    ?array $nsPrefixes = null
): int|false
public DOMNode::cloneNode(bool $deep = false): DOMNode|false
public DOMNode::getLineNo(): int
public DOMNode::getNodePath(): ?string
public DOMNode::hasAttributes(): bool
public DOMNode::hasChildNodes(): bool
public DOMNode::insertBefore(DOMNode $node, ?DOMNode $child = null): DOMNode|false
public DOMNode::isDefaultNamespace(string $namespace): bool
public DOMNode::isSameNode(DOMNode $otherNode): bool
public DOMNode::isSupported(string $feature, string $version): bool
public DOMNode::lookupNamespaceUri(string $prefix): string
public DOMNode::lookupPrefix(string $namespace): ?string
public DOMNode::normalize(): void
public DOMNode::removeChild(DOMNode $child): DOMNode|false
public DOMNode::replaceChild(DOMNode $node, DOMNode $child): DOMNode|false
}

属性

childElementCount

The number of child elements.

firstElementChild

First child element or null.

lastElementChild

Last child element or null.

nextElementSibling

The next sibling element or null.

previousElementSibling

The previous sibling element or null.

schemaTypeInfo

Not implemented yet, always return null

tagName

The element name

更新日志

版本 说明
8.0.0 The firstElementChild, lastElementChild, childElementCount, previousElementSibling, and nextElementSibling properties have been added.
8.0.0 DOMElement implements DOMParentNode and DOMChildNode now.

注释

注意:

此 DOM 扩展采用 UTF-8 编码。在 ISO-8859-1 编码下,使用 utf8_encode()utf8_decode() 来处理,其它编码下使用 iconv 函数处理。

目录

add a noteadd a note

User Contributed Notes 13 notes

up
107
j DOT wagner ( AT ) medieninnovation.com
13 years ago
Caveat!
It took me almost an hour to figure this out, so I hope it saves at least one of you some time.

If you want to debug your DOM tree and try var_dump() or similar you will be fooled into thinking the DOMElement that you are looking at is empty, because var_dump() says: object(DOMElement)#1 (0) { }

After much debugging I found out that all DOM objects are invisible to var_dump() and print_r(), my guess is because they are C objects and not PHP objects. So I tried saveXML(), which works fine on DOMDocument, but is not implemented on DOMElement.

The solution is simple (if you know it):
$xml = $domElement->ownerDocument->saveXML($domElement);

This will give you an XML representation of $domElement.
up
61
Pinochet
13 years ago
Hi to get the value of DOMElement just get the nodeValue public parameter (it is inherited from DOMNode):
<?php
echo $domElement->nodeValue;
?>
Everything is obvious if you now about this thing ;-)
up
36
Janne Enberg
8 years ago
This page doesn't list the inherited properties from DOMNode, e.g. the quite important textContent property. It would be immensely helpful if it would list those as well.
up
26
dpetroff ( at ) gmail.com
11 years ago
Hi!

Combining all th comments, the easiest way to get inner HTML of the node is to use this function:

<?php
function get_inner_html( $node ) {
   
$innerHTML= '';
   
$children = $node->childNodes;
    foreach (
$children as $child) {
       
$innerHTML .= $child->ownerDocument->saveXML( $child );
    }

    return
$innerHTML;
}
?>
up
8
Daniel Morlock
13 years ago
It would be nice to have a function which converts a document/node/element into a string.

Anyways, I use the following code snippet to get the innerHTML value of a DOMNode:

<?php
function getInnerHTML($Node)
{
    
$Body = $Node->ownerDocument->documentElement->firstChild->firstChild;
    
$Document = new DOMDocument();    
    
$Document->appendChild($Document->importNode($Body,true));
     return
$Document->saveHTML();
}
?>
up
4
patrick smith
13 years ago
Although it may be preferable to use the dom to manipulate elements, sometimes it's useful to actually get the innerHTML from a document element (e.g. to load into a client-side editor).

To get the innerHTML of a specific element ($elem_id) in a specific html file ($filepath):

<?php
$innerHTML
= '';
$doc = new DOMDocument();
$doc->loadHTMLFile($filepath);   
$elem = $doc->getElementById($elem_id);

// loop through all childNodes, getting html       
$children = $elem->childNodes;
foreach (
$children as $child) {
   
$tmp_doc = new DOMDocument();
   
$tmp_doc->appendChild($tmp_doc->importNode($child,true));       
   
$innerHTML .= $tmp_doc->saveHTML();
}
?>
up
3
felix dot klee at inka dot de
9 years ago
How to rename an element and preserve attributes:

<?php

// Changes the name of element $element to $newName.
function renameElement($element, $newName) {
 
$newElement = $element->ownerDocument->createElement($newName);
 
$parentElement = $element->parentNode;
 
$parentElement->insertBefore($newElement, $element);

 
$childNodes = $element->childNodes;
  while (
$childNodes->length > 0) {
   
$newElement->appendChild($childNodes->item(0));
  }

 
$attributes = $element->attributes;
  while (
$attributes->length > 0) {
   
$attribute = $attributes->item(0);
    if (!
is_null($attribute->namespaceURI)) {
     
$newElement->setAttributeNS('http://www.w3.org/2000/xmlns/',
                                 
'xmlns:'.$attribute->prefix,
                                 
$attribute->namespaceURI);
    }
   
$newElement->setAttributeNode($attribute);
  }

 
$parentElement->removeChild($element);
}

function
prettyPrint($d) {
 
$d->formatOutput = true;
  echo
'<pre>'.htmlspecialchars($d->saveXML()).'</pre>';
}

$d = new DOMDocument( '1.0' );
$d->loadXML('<?xml version="1.0"?>
<library>
  <data a:foo="1" x="bar" xmlns:a="http://example.com/a">
    <invite>
      <username>jmansa</username>
      <userid>1</userid>
    </invite>
    <update>1</update>
  </data>
</library>'
);

$xpath = new DOMXPath($d);
$elements = $xpath->query('/library/data');
if (
$elements->length == 1) {
 
$element = $elements->item(0);
 
renameElement($element, 'invites');
}

prettyPrint($d);

?>
up
2
ae.fxx
13 years ago
Hi there.

Remember to append a DOMNode (or any of its descendants) to a DOMDocument __BEFORE__ you try to append a child to it.

I don't know why it has to be this way but it can't be done without it.

bye
up
1
nawaman at gmail dot com
12 years ago
The following code shows can text-only content be extracted from a document.

<?php
function getTextFromNode($Node, $Text = "") {
    if (
$Node->tagName == null)
        return
$Text.$Node->textContent;

   
$Node = $Node->firstChild;
    if (
$Node != null)
       
$Text = getTextFromNode($Node, $Text);

    while(
$Node->nextSibling != null) {
       
$Text = getTextFromNode($Node->nextSibling, $Text);
       
$Node = $Node->nextSibling;
    }
    return
$Text;
}

function
getTextFromDocument($DOMDoc) {
    return
getTextFromNode($DOMDoc->documentElement);
}

$Doc = new DOMDocument();
$Doc->loadHTMLFile("Test.html");
echo
getTextFromDocument($Doc)."\n";
?>
up
0
johnny
8 years ago
Get html of a node
$html .= $dom->saveHTML($node);
up
0
loopduplicate at burningtoken dot com
11 years ago
This works perfect for me as well:

<?php $xml = $domElement->ownerDocument->saveXML($domElement); ?>
up
-1
Anonymous
11 years ago
you can use DOMNode::nodeValue
DOMElement inherits this public property.

$elem->nodeValue
up
-3
Severin
13 years ago
I wanted to find similar Elements - thats why I built an Xpath-String like this - maybe somebody needs it... its not very pretty - but neither is domdocument :)

<?php

$dom
->load($xmlFile))

$xpathQuery = '//*';
$xmlNodes = $xpath->query($xpathQuery);
       
$pathlist = array();
$attrlist = array();
foreach (
$xmlNodes as $node) {

 
$depth = $this->_getDomDepth($node);   //get Path-Depth (for array key)
 
$pathlist[$depth] = $node->tagName;     // tagname
         
 
$attrs = $node->attributes;
 
$attr='';
 
$a=0;
  foreach (
$attrs as $attrName => $attrNode// attributes
           
{
              if (
$attrName !='reg')
              {
                if (
$a++!=0) $attr .= ' and ';
               
$attr .= '@'.$attrName.'='."'".$attrNode->value."'";
              }
            }
         
         
$attrlist[$depth] = $attr?'['.$attr.']':'';
         
         
$path = ''; for ($i=0;$i<=$depth;$i++) $path .= '/'.$pathlist[$i].$attrlist[$i];  // the xpath of the actual Element

    // ... now you can go on and user $path to find similar elements
   
}
  }
}

private function
_getDomDepth(DomNode $node)
   {
    
$r = -2;
     while (
$node) {
      
$r++; 
      
$node = $node->parentNode;
     }
     return 
$r;
   }
?>

官方地址:https://www.php.net/manual/en/class.domelement.php

冷却塔厂家 广告
-- 广告
北京半月雨文化科技有限公司.版权所有 京ICP备12026184号-3