PHP/XML/DomDocument

Материал из Web эксперт
Перейти к: навигация, поиск

Append children

   <source lang="html4strict">

<?php $root = new DomDocument ( "1.0", "iso-8859-1" ); $html = $root->createElement ( "html" ); $body = $root->createElement ( "body" ); $table = $root->createElement ( "table" ); $row = $root->createElement ( "tr" ); $cell = $root->createElement ( "td", "value1" ); $row->appendChild ( $cell ); $cell = $root->createElement ( "td", "value2" ); $row->appendChild ( $cell ); $table->appendChild ( $row ); $body->appendChild ( $table ); $html->appendChild ( $body ); $root->appendChild ( $html ); $row = $root->createElement ( "tr" ); $cell = $root->createElement ( "td", "value3" ); $row->appendChild ( $cell ); $cell = $root->createElement ( "td", "value4" ); $row->appendChild ( $cell ); $table->appendChild ( $row ); echo $root->saveHTML (); ?>

 </source>
   
  


Constructing an XML Document with the DOM Functions

   <source lang="html4strict">

<?php $news = array(

 array( "headline" => "header",
   "image" => "high.gif",
   "byline" => "line",
   "article" => "news",
   "type" => "short"
   )

);

$doc = new DomDocument("1.0"); $root = $doc->appendChild( $doc->createElement("banana-news") ); foreach( $news as $newselement ) {

 $item = $root->appendChild( $doc->createElement( "newsitem") );
 $item->setAttribute( "type", $newselement["type"] );
 foreach( array("headline", "image", "byline") as $tagname ) {
   $el = $doc->createElement( $tagname );
   $item->appendChild( $el );
   $text = $doc->createTextNode( $newselement[$tagname] );
   $el->appendChild( $text );
 }

} print $doc->saveXML( );

 </source>
   
  


Create element with DomDocument

   <source lang="html4strict">

<?php

  1. load an XML document into the DOM

$dom = new DomDocument(); $dom -> load("books.xml"); $title = $dom -> createElement("title");

  1. create text nodes

$topictext = $dom -> createTextNode("Linux");

  1. append the text nodes to the inner nested elements

$topic -> appendChild($topictext);

  1. append the inner nested elements to the <title> element

$title -> appendChild($topic);

  1. append the <title> element to the root element

$dom -> documentElement -> appendChild($title);

  1. create a new enlarged xml document

$dom -> save("newbooks.xml"); ?>

 </source>
   
  


Create the script that uses the DOM extension to create a list of title and book_id attributes.

   <source lang="html4strict">

<?php $doc = DOMDocument::load("books.xml"); $books = $doc->getElementsByTagName("book"); foreach($books as $book) {

 $titles = $book->getElementsByTagName("title");
 foreach($titles as $title) {
   echo $title->nodeValue . " - ";
 }
 $id = $book->getAttribute("book_id");
   echo "book_id = $id\n";

} ?>

 </source>
   
  


Creating and Setting Attributes

   <source lang="html4strict">

<?php $root = new DomDocument("1.0", "iso-8859-1"); $html = $root->createElement("html"); $body = $root->createElement("body"); $table = $root->createElement("table"); $w = $root->createAttribute("width"); $table->appendChild($w); $h = $root->createAttribute("height"); $table->appendChild($h); $b = $root->createAttribute("border"); $table->appendChild($b); $table->setAttribute("width", "100%"); $table->setAttribute("height", "50%"); $table->setAttribute("border", "1"); $row = $root->createElement("tr"); $cell = $root->createElement("td", "value1"); $row->appendChild($cell); $cell = $root->createElement("td", "value2"); $row->appendChild($cell); $table->appendChild($row); $body->appendChild($table); $html->appendChild($body); $root->appendChild($html); echo $root->saveHTML(); ?>

 </source>
   
  


DOM editing with DomDocument

   <source lang="html4strict">

<?php $root = new DomDocument("1.0", "iso-8859-1"); $html = $root->createElement("html"); $body = $root->createElement("body"); $table = $root->createElement("table"); $row = $root->createElement("tr"); $cell = $root->createElement("td", "value1"); $row->appendChild($cell); $cell = $root->createElement("td", "value2"); $row->appendChild($cell); $table->appendChild($row); $body->appendChild($table); $html->appendChild($body); $root->appendChild($html); $row = $root->createElement("tr"); $cell = $root->createElement("td", "value3"); $row->appendChild($cell); $cell = $root->createElement("td", "value4"); $row->appendChild($cell); $table->appendChild($row); echo $root->saveHTML(); ?>

 </source>
   
  


Get element by tag name

   <source lang="html4strict">

<?php $doc = DOMDocument::load("books.xml"); $books = $doc->getElementsByTagName("book"); foreach($books as $book) {

   $titles = $book->getElementsByTagName("title"); 
   foreach($titles as $title) { 
       echo $title->nodeValue . " - "; 
   } 
   $id = $book->getAttribute("book_id"); 
   echo "book_id = $id\n"; 

} ?>

 </source>
   
  


Loading from server

   <source lang="html4strict">

<?php $data = DOMDocument::load ( "http://data.org/data.xml" ); $stories = $data->getElementsByTagName ( "story" ); foreach ( $stories as $story ) {

 $titles = $story->getElementsByTagName ( "title" );
 foreach ( $titles as $title ) {
   echo $title->nodeValue . " - ";
 }

} ?>

 </source>
   
  


Loads the content of this file into a DOM object tree.

   <source lang="html4strict">

<?php $data = DOMDocument::load("http://data.org/data.xml"); ?>

 </source>
   
  


Parsing XML

   <source lang="html4strict">

<?php $doc = DOMDocument::loadHTMLFile("http://php.net"); echo $doc->saveHTML(); ?>

 </source>
   
  


Remove the creation and appending of attributes and simply assign the needed attributes to the elements

   <source lang="html4strict">

<?php $root = new DomDocument("1.0", "iso-8859-1"); $html = $root->createElement("html"); $body = $root->createElement("body"); $table = $root->createElement("table"); $table->setAttribute("width", "100%"); $table->setAttribute("height", "50%"); $table->setAttribute("border", "1"); $row = $root->createElement("tr"); $cell = $root->createElement("td", "value1"); $row->appendChild($cell); $cell = $root->createElement("td", "value2"); $row->appendChild($cell); $table->appendChild($row); $body->appendChild($table); $html->appendChild($body); $root->appendChild($html); echo $root->saveHTML(); ?>

 </source>
   
  


Return a list of nodes that can be examined one at the time in a foreach() loop

   <source lang="html4strict">

<?php $data = DOMDocument::load("http://yourdomain.org/data.xml"); $stories = $data->getElementsByTagName("story"); foreach($stories as $story) {

 $titles = $story->getElementsByTagName("title");
 foreach($titles as $title) {
   echo $title->nodeValue . " - ";
 }
 $urls = $story->getElementsByTagName("url");
 foreach($urls as $url) {
   echo $url->nodeValue . "\n";
 }

} ?>

 </source>
   
  


Sample Transformation File test-php5.php

   <source lang="html4strict">

<?php

     $path_xml = "f.xml";
     $path_style = "f.xsl";
     $xml_obj = new DomDocument;
     $xsl_obj = new DomDocument;
     if (!$xml_obj->load($path_xml)) {
          echo "Error! Unable to open " . $path_xml . "!\n";
          exit;
      }
      if (!$xsl_obj->load($path_style)) {
          echo "Error! Unable to open " . $path_style . "!\n";
          exit;
      }
      $xslt_parse = new xsltprocessor;
      $xslt_parse->importStyleSheet($xsl_obj);
      echo $xslt_parse->transformToXML($xml_obj);
  ?>
 
 </source>
   
  


Traversing a Tree of XML Nodes Using On-Demand Functions

   <source lang="html4strict">

<?php $doc = new DomDocument("1.0"); $doc->loadXML( file_get_contents("data.xml") ); $root = $doc->firstChild; $pointer = $root; do {

 print $pointer->tagName."
\n";

} while ( $pointer = next_element( $pointer ) ); function next_element( DomNode $pointer ) {

 while ( $pointer = next_node( $pointer ) ) {
   if ( $pointer->nodeType == XML_ELEMENT_NODE ) {
     return $pointer;
   }
 }
 return false;

} function next_node( DomNode $pointer ) {

 if ( $pointer->hasChildNodes() ) {
   return $pointer->firstChild ;
 }
 if ( $next = $pointer->nextSibling ) {
   return $next;
 }
 while( $pointer = $pointer->parentNode ) {
   if ( $next=$pointer->nextSibling ) {
     return $next;
   }
 }

} ?>

 </source>
   
  


Traversing a Tree of XML Nodes Using Recursion

   <source lang="html4strict">

<?php $doc = new DomDocument("1.0"); $doc->loadXML( file_get_contents("data.xml") ); $root = $doc->firstChild; traverse( $root ); function traverse( DomNode $node, $level=0 ){

 handle_node( $node, $level );
if ( $node->hasChildNodes() ) {
  $children = $node->childNodes;
  foreach( $children as $kid ) {
    if ( $kid->nodeType == XML_ELEMENT_NODE ) {
      traverse( $kid, $level+1 );
    }
  }
}

} function handle_node( DomNode $node, $level ) {

 for ( $x=0; $x<$level; $x++ ) {
   print " ";
 }
 if ( $node->nodeType == XML_ELEMENT_NODE ) {
   print $node->tagName."
\n"; }

} ?>

 </source>
   
  


Use the createTextNode() method to add multiple text strings to a body element in an HTML document.

   <source lang="html4strict">

<?php $root = new DomDocument("1.0", "iso-8859-1"); $html = $root->createElement("html"); $body = $root->createElement("body"); $txt = $root->createTextNode(utf8_encode("Danish characters ?\n")); $body->appendChild($txt); $txt = $root->createTextNode(utf8_encode("&")); $body->appendChild($txt); $html->appendChild($body); $root->appendChild($html); echo $root->saveHTML(); ?>

 </source>
   
  


Using CDATA sections, or character data sections

   <source lang="html4strict">

<?php $root = new DomDocument ( "1.0", "iso-8859-1" ); $html = $root->createElement ( "html" ); $body = $root->createElement ( "body" ); $script = $root->createElement ( "script" ); $txt = $root->createCDATASection ( "function SubmitForm() {

 if (document.myform.name.value == "") { 
   alert("Name cannot be empty"); 
   document.myform.name.focus(); 
 } 

}" ); $script->appendChild ( $txt ); $body->appendChild ( $script ); $html->appendChild ( $body ); $root->appendChild ( $html ); header ( "Content-Type: text/xml" ); echo $root->saveXML (); ?>

 </source>
   
  


Using DOM to Generate Markup

   <source lang="html4strict">

<?php $root = new DomDocument("1.0", "iso-8859-1"); $html = $root->createElement("html"); $body = $root->createElement("body"); $table = $root->createElement("table"); $row = $root->createElement("tr"); $cell = $root->createElement("td", "value1"); $row->appendChild($cell); $cell = $root->createElement("td", "value2"); $row->appendChild($cell); $table->appendChild($row); $body->appendChild($table); $html->appendChild($body); $root->appendChild($html); echo $root->saveHTML(); ?>

 </source>
   
  


Using XPath with DOM in a more complicated example

   <source lang="html4strict">

<? $dom = new DOMDocument; $dom->load("address-book.xml"); $xpath = new DOMXPath($dom); $person = $xpath->query("/address-book/person"); foreach ($person as $p) {

   $fn = $xpath->query("firstname", $p);
   $firstname = $fn->item(0)->firstChild->nodeValue;
   $ln = $xpath->query("lastname", $p);
   $lastname = $ln->item(0)->firstChild->nodeValue;
   print "$firstname $lastname\n";

} ?> // <?xml version="1.0"?> <address-book>

   <person id="1">
       <firstname>D</firstname>
       <lastname>S</lastname>
       <city>New York</city>
       <state>NY</state>
       <email>s@php.net</email>
   </person>
   <person id="2">
       <firstname>A</firstname>
       <lastname>T</lastname>
       <city>San Francisco</city>
       <state>CA</state>
       <email>a@php.net</email>
   </person>

</address-book>

 </source>
   
  


Validating an XML document

   <source lang="html4strict">

<? $file = "address-book.xml"; $schema = "address-book.xsd"; $ab = new DOMDocument; $ab->load($file); if ($ab->schemaValidate($schema)) {

   print "$file is valid.\n";

} else {

   print "$file is invalid.\n";

} ?>

 </source>