dcsimg
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

Accessing and Manipulating the DOM with PHP : Page 4

Discover how to create a DOM tree from scratch or modify an existing DOM tree using PHP 5.


advertisement

Importing Nodes

Use the importNode method to copy a node from another tree to the current tree:

DOMNode DOMDocument::importNode(DOMNode $importedNode [,bool $deep]): This method imports a node from another XML document and inserts it into the current document's DOM tree. The $importedNode argument specifies the node to import. The imported node represents a copy of the original node, so the import does not alter the external tree. The $deep argument controls whether the method imports a deep copy of the imported node. When TRUE, the method imports the entire node subtree; when FALSE, it imports only the node.

As an example, this next application imports the <continue> node from the Book_continue.xml file into Book.xml. First, here's the Book_continue.xml document contents:

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<!--chapter V-->
<continue>
  <chapter_V>
   <title>XPath</title>
   <content>XPath is language for...</content>
  </chapter_V>
  
  <![CDATA[
     This chaper is a bonus to...
     ]]>
  
  <printing cap_I="click_here_for_chapter_I" 
    cap_II="click_here_for_chapter_II"   
    cap_III="click_here_for_chapter_III"
    cap_IV="click_here_for_chapter_IV" 
    cap_V="click_here_for_chapter_V" />
  
</continue>

And here's the code to import the <continue> node:

<?php
$olddoc = new DOMDocument;
$olddoc->load("Book_continue.xml");
// The node we want to import to a new document
$node = $olddoc->getElementsByTagName("continue")->item(0);
$newdoc = new DOMDocument;
$newdoc->formatOutput = true;
$newdoc->load("Book.xml");
// Import the node, and all its children, to the document
$node = $newdoc->importNode($node, true);
// And then append it to the root node
$newdoc->documentElement->appendChild($node);
echo "\nThe 'new document' after copying the nodes into it:\n";
$root = $newdoc->firstChild;
function getNodesInfo($node)
{
   if ($node->hasChildNodes())
   {
      $subNodes = $node->childNodes;
      foreach ($subNodes as $subNode)
      {
         if (($subNode->nodeType != 3) || 
            (($subNode->nodeType ==3) &&
            (strlen(trim($subNode->wholeText))>=1)))   
         {
         echo "Node name: ".$subNode->nodeName."\n";
         echo "Node value: ".$subNode->nodeValue."\n";
      }
      getNodesInfo($subNode);         
      }
   }      
}
getNodesInfo($root);   
?>

Figure 7 shows the output from the preceding code.

 
Figure 7. Imported Node: Here's what Book.xml looks like after importing the node from the Book_continue.xml and placing it at the end of the Book.xml tree.

Checking Node Equality

To check whether two nodes are the same use the function isSameNode:

bool DOMNode::isSameNode(DOMNode $node): This function returns a Boolean TRUE when the nodes are equal, and FALSE otherwise. The $node argument represents the node to which you want to compare the current node.

Note that the comparison is not based on the content of the nodes.

//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";
   }   
}

Creating a New Tree

You don't have to start with an existing tree; the DOM extension for PHP 5 lets you build trees from scratch. The following example creates a completely new XML document. It also uses two new functions that let you create a comment and CDATA nodes:

  • DOMComment DOMDocument::createComment(string $data): Create a new comment node. The $data argument represents the node content.
  • DOMCDATASection DOMDocument::createCDATASection(string $data): Create a new CDATA node. The $data argument represents the node content.

The example in Listing 2 creates an object tree and saves it as Flowers.xml.

The new Flower.xml document looks like this:

<?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>
]]>

This brief introduction to the DOM extension for PHP 5 should give you enough background to manipulate existing XML (or HTML) documents, or to create them from scratch.



Octavia Andreea Anghel is a senior PHP developer currently working as a primary trainer for programming teams that participate at national and international software-development contests. She consults on developing educational projects at a national level. She is a coauthor of the book "XML Technologies—XML in Java" (Albastra, ISBN 978-973-650-210-1), for which she wrote the XML portions. In addition to PHP and XML, she's interested in software architecture, web services, UML, and high-performance unit tests.
Thanks for your registration, follow us on our social networks to keep up-to-date