PHP Conference Japan 2024

DOMElement 類別

(PHP 5、PHP 7、PHP 8)

類別概要

class DOMElement extends DOMNode implements DOMParentNode, DOMChildNode {
/* 繼承的常數 */
/* 屬性 */
public readonly string $tagName
public string $className
public string $id
public readonly mixed $schemaTypeInfo
public readonly ?DOMElement $firstElementChild
public readonly ?DOMElement $lastElementChild
public readonly int $childElementCount
public readonly ?DOMElement $nextElementSibling
/* 繼承的屬性 */
public readonly string $nodeName
public ?string $nodeValue
public readonly int $nodeType
public readonly ?DOMNode $parentNode
public readonly ?DOMElement $parentElement
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 bool $isConnected
public readonly ?DOMDocument $ownerDocument
public readonly ?string $namespaceURI
public string $prefix
public readonly ?string $localName
public readonly ?string $baseURI
/* 方法 */
public __construct(string $qualifiedName, ?string $value = null, string $namespace = "")
public after(DOMNode|string ...$nodes): void
public append(DOMNode|string ...$nodes): void
public before(DOMNode|string ...$nodes): void
public getAttribute(string $qualifiedName): string
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 insertAdjacentText(string $where, string $data): void
public prepend(DOMNode|string ...$nodes): void
public remove(): void
public removeAttribute(string $qualifiedName): bool
public removeAttributeNS(?string $namespace, string $localName): void
public replaceChildren(DOMNode|string ...$nodes): void
public replaceWith(DOMNode|string ...$nodes): void
public setAttribute(string $qualifiedName, string $value): DOMAttr|bool
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 toggleAttribute(string $qualifiedName, ?bool $force = null): bool
/* 繼承的方法 */
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::isEqualNode(?DOMNode $otherNode): bool
public DOMNode::isSameNode(DOMNode $otherNode): bool
public DOMNode::isSupported(string $feature, string $version): bool
}

屬性

childElementCount

子元素的數量。

firstElementChild

第一個子元素,若無則為 null

lastElementChild

最後一個子元素,若無則為 null

nextElementSibling

下一個兄弟元素,若無則為 null

previousElementSibling

上一個兄弟元素,若無則為 null

schemaTypeInfo

尚未實作,總是回傳 null

tagName

元素名稱

className

一個字串,表示元素的類別,以空格分隔

id

元素 ID

變更日誌

版本 描述
8.0.0 新增了 firstElementChildlastElementChildchildElementCountpreviousElementSiblingnextElementSibling 屬性。
8.0.0 DOMElement 現在實作了 DOMParentNodeDOMChildNode

注意

注意:

DOM 擴充功能使用 UTF-8 編碼。使用 mb_convert_encoding()UConverter::transcode()iconv() 來處理其他編碼。

目錄

新增註解

使用者貢獻的註解 13 則註解

j DOT wagner ( AT ) medieninnovation.com
16 年前
注意事項!
我花了一個小時才搞清楚這個問題,所以我希望至少可以為你們其中一人節省一些時間。

如果您想除錯您的 DOM 樹並嘗試 var_dump() 或類似的函式,您會被誤導地認為您正在檢視的 DOMElement 是空的,因為 var_dump() 會顯示:object(DOMElement)#1 (0) { }

經過多次除錯後,我發現所有 DOM 物件對於 var_dump() 和 print_r() 都是不可見的,我猜是因為它們是 C 物件而不是 PHP 物件。所以我嘗試了 saveXML(),它在 DOMDocument 上運作良好,但在 DOMElement 上沒有實作。

解決方案很簡單(如果您知道的話)
$xml = $domElement->ownerDocument->saveXML($domElement);

這會給您 $domElement 的 XML 表示。
Pinochet
16 年前
嗨,要取得 DOMElement 的值,只需取得 nodeValue 公用參數(它繼承自 DOMNode)
<?php
echo $domElement->nodeValue;
?>
如果您知道這個東西,一切都很明顯了 ;-)
Janne Enberg
11 年前
此頁面沒有列出從 DOMNode 繼承的屬性,例如非常重要的 textContent 屬性。如果也能列出這些屬性將會非常有幫助。
dpetroff ( at ) gmail.com
14 年前
嗨!

結合所有註解,取得節點內部 HTML 最簡單的方法是使用此函式

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

return
$innerHTML;
}
?>
Daniel Morlock
15 年前
如果有一個函式可以將文件/節點/元素轉換為字串會很好。

無論如何,我使用以下程式碼片段來取得 DOMNode 的 innerHTML 值

<?php
function getInnerHTML($Node)
{
$Body = $Node->ownerDocument->documentElement->firstChild->firstChild;
$Document = new DOMDocument();
$Document->appendChild($Document->importNode($Body,true));
return
$Document->saveHTML();
}
?>
felix dot klee at inka dot de
11 年前
如何重新命名元素並保留屬性

<?php

// 將元素 $element 的名稱變更為 $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);

?>
patrick smith
16 年前
雖然最好使用 DOM 來操作元素,但有時實際從文件元素取得 innerHTML 是有用的(例如,載入到用戶端編輯器)。

若要取得特定 HTML 檔案($filepath)中特定元素($elem_id)的 innerHTML

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

// 迴圈遍歷所有子節點,取得 html
$children = $elem->childNodes;
foreach (
$children as $child) {
$tmp_doc = new DOMDocument();
$tmp_doc->appendChild($tmp_doc->importNode($child,true));
$innerHTML .= $tmp_doc->saveHTML();
}
?>
ae.fxx
16 年前
嗨,大家好。

請記住,在嘗試將子節點附加到 DOMDocument 之前,請先將 DOMNode(或其任何後代)附加到 DOMDocument。

我不知道為什麼必須這樣做,但沒有這樣做就無法完成。

johnny
10 年前
取得節點的 HTML
$html .= $dom->saveHTML($node);
Anonymous
13 年前
您可以使用 DOMNode::nodeValue
DOMElement 繼承了這個公開屬性。

$elem->nodeValue
loopduplicate at burningtoken dot com
13 年前
這個方法對我來說也完美運作。

<?php $xml = $domElement->ownerDocument->saveXML($domElement); ?>
nawaman at gmail dot com
15 年前
以下程式碼展示如何從文件中提取純文字內容。

<?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";
?>
Severin
16 年前
我想要找到相似的元素 - 這就是我建立像這樣的 Xpath 字串的原因 - 也許有人會需要它...它不是很漂亮 - 但 domdocument 也不是 :)

<?php

$dom
->load($xmlFile))

$xpathQuery = '//*';
$xmlNodes = $xpath->query($xpathQuery);

$pathlist = array();
$attrlist = array();
foreach (
$xmlNodes as $node) {

$depth = $this->_getDomDepth($node); //取得路徑深度(用於陣列鍵)
$pathlist[$depth] = $node->tagName; // 標籤名稱

$attrs = $node->attributes;
$attr='';
$a=0;
foreach (
$attrs as $attrName => $attrNode) // 屬性
{
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]; // 實際元素的 xpath

// ... 現在你可以繼續使用 $path 來尋找相似的元素
}
}
}

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