PHPのお勉強!

PHP TOP

DOMElement クラス

(PHP 5, PHP 7, PHP 8)

クラス概要

class DOMElement extends DOMNode implements DOMParentNode, DOMChildNode {
/* プロパティ */
public readonly string $tagName;
public string $id;
public readonly mixed $schemaTypeInfo = null;
public readonly ?DOMElement $firstElementChild;
public readonly ?DOMElement $lastElementChild;
public readonly int $childElementCount;
/* 継承したプロパティ */
public readonly string $nodeName;
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 プロパティ firstElementChild, lastElementChild, childElementCount, previousElementSibling, nextElementSibling が追加されました。
8.0.0 DOMElement は、 DOMParentNodeDOMChildNode を実装しました。

注意

注意:

DOM拡張モジュール は UTF-8 エンコーディングを使います。他のエンコーディングを扱う場合は、mb_convert_encoding(), UConverter::transcode(), iconv() を使ってください。

目次

add a note

User Contributed Notes 13 notes

up
118
j DOT wagner ( AT ) medieninnovation.com
16 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
62
Pinochet
15 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
38
Janne Enberg
10 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
13 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
10
Daniel Morlock
15 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
felix dot klee at inka dot de
11 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);

?>