ノードの等値性をチェックする
2つのノードが同じかチェックするには関数isSameNodeを使います。
bool DOMNode::isSameNode(DOMNode $node)
この関数は、ノードが等しいときは論理値のTRUEを返し、等しくないときはFALSEを返します。引数$nodeは現在のノードと比較するノードです。この比較はノードのコンテンツに基づいて行われるものではないことに注意してください。
//Checking if two nodes are equals
$author1 = $root->getElementsByTagName('autor')->item(0);
$author2 = $root->getElementsByTagName('autor')->item(1);
//The verifyNodes function call
verifyNodes($author1,$author2);
function verifyNodes($currentNode, $node)
{
if (($currentNode->isSameNode($node))==true)
{
echo "These two nodes are the same";
}
}
新しいツリーを作成する
既存のツリーを最初から使わなくてもかまいません。PHP 5のDOMエクステンションではツリーをゼロから作ることもできます。次の例では、まったく新しいXML文書を作成します。ここではコメントノードを作成する関数とCDATAノードを作成する関数を使用しています。
DOMComment DOMDocument::createComment(string $data)
新しいコメントノードを作成します。引数$dataはノードのコンテンツです。
DOMCDATASection DOMDocument::createCDATASection(string $data)
新しいCDATAノードを作成します。引数$dataはノードのコンテンツです。
リスト2の例ではオブジェクトツリーを作成し、Flowers.xmlという名前で保存します。
<?php
//Create a document instance
$document = new DOMDocument();
//Formats output with indentation
$document->formatOutput = true;
//Create a comment
$comment = $document->createComment('Beautiful flowers!!!');
$document->appendChild( $comment );
//Create the <flowers> root element
$root = $document->createElement( 'flowers' );
$document->appendChild( $root );
//Create the <tulips> children of the root
$tulips = $document->createElement( 'tulips' );
//Create the first child of the <tulips> element,<bulbs>,
// and set its attribute
$bulbs_1 = $document->createElement( 'bulbs' );
$bulbs_1->setAttribute('price','€ 7.65');
$bulbs_1->appendChild($document->createTextNode( 'Parrot'));
$tulips->appendChild( $bulbs_1 );
//Create the second child of the <tulips> element,<bulbs>,
// and set its attribute
$bulbs_2 = $document->createElement( 'bulbs' );
$bulbs_2->setAttribute('color','magenta');
$bulbs_2->appendChild($document->createTextNode( 'Lily flowering' ));
$tulips->appendChild( $bulbs_2 );
//Append the <tulips> node to the root
$root->appendChild( $tulips );
//Create a CDATA section
$cdata = $document->createCDATASection(
'<gladiolus><species>Sword Lily</species>'.
'<species>Starface</species></gladiolus>');
$document->appendChild( $cdata );
//Save the object tree to Flowers.xml
echo $document->saveXML();
$document->save('Flowers.xml');
?>
新しい文書Flower.xmlは次のようになります。
<?xml version="1.0" encoding="ISO-8859-1"?>
<!--Beautiful flowers!!!-->
<flowers>
<tulips>
<bulbs price="€ 7.65">Parrot</bulbs>
<bulbs color="magenta">Lily flowering</bulbs>
</tulips>
</flowers>
<![CDATA[<gladiolus>
<species>Sword Lily</species>
<species>Starface</species>
</gladiolus>
]]>
以上、PHP 5のDOMエクステンションを簡単に紹介しました。これらの情報は既存のXML(HTML)文書を操作したり、文書をゼロから作成したりするときに役立つはずです。
