1 读取XML
<?php
$xml=new DOMDocument('1.0','UTF-8');
//加载Xml文件
$xml->load('test.xml');
// 获取所有的post标签
$postDom = $xml->getElementsByTagName('post');
// 循环遍历post标签
foreach($postDom as $post)
{
// 获取Title标签Node
$title = $post->getElementsByTagName('title');
/\*\*
\* 要获取Title标签的Id属性要分两部走
\* 1. 获取title中所有属性的列表也就是$title->item(0)->attributes
\* 2. 获取title中id的属性,因为其在第一位所以用item(0)
\*
\* 小提示:
\* 若取属性的值可以用item(\*)->nodeValue
\* 若取属性的标签可以用item(\*)->nodeName
\* 若取属性的类型可以用item(\*)->nodeType
\*/
echo 'Id: ' . $title->item(0)->attributes->item(0)->nodeValue . '<br />';
echo 'Title: ' . $title->item(0)->nodeValue . '<br />';
echo 'Details: ' . $post->getElementsByTagName('details')->item(0)->nodeValue . '<br /><br />';
}
?>
2 生成XML
<?php // $books = array(); // $books [] = array( // 'title' => 'PHP Hacks', // 'author' => 'Jack Herrington', // 'publisher' => "O'Reilly" // ); // $books [] = array( // 'title' => 'Podcasting Hacks', // 'author' => 'Jack Herrington', // 'publisher' => "O'Reilly" // ); // // $doc = new DOMDocument(); // $doc->formatOutput = true; // // $r = $doc->createElement( "books" ); // $doc->appendChild( $r ); // // foreach( $books as $book ) // { // $b = $doc->createElement( "book" ); // // $author = $doc->createElement( "author" ); // $author->appendChild( // $doc->createTextNode( $book['author'] ) // ); // $b->appendChild( $author ); // // $title = $doc->createElement( "title" ); // $title->appendChild( // $doc->createTextNode( $book['title'] ) // ); // $b->appendChild( $title ); // // $publisher = $doc->createElement( "publisher" ); // $publisher->appendChild( // $doc->createTextNode( $book['publisher'] ) // ); // $b->appendChild( $publisher ); // // $r->appendChild( $b ); // } // // header("Content-Type:text/xml"); // echo $doc->saveXML(); $dom=new DOMDocument("1.0",'UTF-8'); header("Content-Type:text/plain"); $root=$dom->createElement( "toppings" ); $dom->appendChild( $root ); $item=$dom->createElement( "item" ); $root->appendChild( $item ); $text=$dom->createTextNode("pepperoni"); $item->appendChild( $text ); //属性 $price=$dom->createAttribute("price"); $item->appendChild( $price ); $priceValue=$dom->createTextNode("4"); $price->appendChild( $priceValue ); echo $dom->saveXML(); ?>