PHP/XML/DomDocument — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
|
(нет различий)
|
Текущая версия на 07:08, 26 мая 2010
Содержание
- 1 Append children
- 2 Constructing an XML Document with the DOM Functions
- 3 Create element with DomDocument
- 4 Create the script that uses the DOM extension to create a list of title and book_id attributes.
- 5 Creating and Setting Attributes
- 6 DOM editing with DomDocument
- 7 Get element by tag name
- 8 Loading from server
- 9 Loads the content of this file into a DOM object tree.
- 10 Parsing XML
- 11 Remove the creation and appending of attributes and simply assign the needed attributes to the elements
- 12 Return a list of nodes that can be examined one at the time in a foreach() loop
- 13 Sample Transformation File test-php5.php
- 14 Traversing a Tree of XML Nodes Using On-Demand Functions
- 15 Traversing a Tree of XML Nodes Using Recursion
- 16 Use the createTextNode() method to add multiple text strings to a body element in an HTML document.
- 17 Using CDATA sections, or character data sections
- 18 Using DOM to Generate Markup
- 19 Using XPath with DOM in a more complicated example
- 20 Validating an XML document
Append children
<?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 ();
?>
Constructing an XML Document with the DOM Functions
<?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( );
Create element with DomDocument
<?php
#load an XML document into the DOM
$dom = new DomDocument();
$dom -> load("books.xml");
$title = $dom -> createElement("title");
#create text nodes
$topictext = $dom -> createTextNode("Linux");
#append the text nodes to the inner nested elements
$topic -> appendChild($topictext);
#append the inner nested elements to the <title> element
$title -> appendChild($topic);
#append the <title> element to the root element
$dom -> documentElement -> appendChild($title);
#create a new enlarged xml document
$dom -> save("newbooks.xml");
?>
Create the script that uses the DOM extension to create a list of title and book_id attributes.
<?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";
}
?>
Creating and Setting Attributes
<?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();
?>
DOM editing with DomDocument
<?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();
?>
Get element by tag name
<?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";
}
?>
Loading from server
<?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 . " - ";
}
}
?>
Loads the content of this file into a DOM object tree.
<?php
$data = DOMDocument::load("http://data.org/data.xml");
?>
Parsing XML
<?php
$doc = DOMDocument::loadHTMLFile("http://php.net");
echo $doc->saveHTML();
?>
Remove the creation and appending of attributes and simply assign the needed attributes to the elements
<?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();
?>
Return a list of nodes that can be examined one at the time in a foreach() loop
<?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";
}
}
?>
Sample Transformation File test-php5.php
<?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);
?>
Traversing a Tree of XML Nodes Using On-Demand Functions
<?php
$doc = new DomDocument("1.0");
$doc->loadXML( file_get_contents("data.xml") );
$root = $doc->firstChild;
$pointer = $root;
do {
print $pointer->tagName."<br />\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;
}
}
}
?>
Traversing a Tree of XML Nodes Using Recursion
<?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."<br />\n";
}
}
?>
Use the createTextNode() method to add multiple text strings to a body element in an HTML document.
<?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();
?>
Using CDATA sections, or character data sections
<?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 ();
?>
Using DOM to Generate Markup
<?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();
?>
Using XPath with DOM in a more complicated example
<?
$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>
Validating an XML document
<?
$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";
}
?>