通过DOM方式PHP可以很方便的创建XML,只是必须要逻辑清晰,不然很容易出错,基本原理如下
$doc = new DOMDocument(‘1.0’, ‘utf-8’); // 声明版本和编码
$doc -> formatOutput = true; $root = $doc -> createElement_x('root'); //创建一个标签
$index = $doc -> createElement_x('index'); //创建一个标签
$id = $doc -> createAttribute(‘id’); //创建一个属性
$newsid = $doc -> createTextNode("1"); //设置属性内容
$newsco = $doc -> createTextNode("content"); //设置标签内容
$id -> a($newsid); //继承属性
$index -> a($id); //继承属性内容
$index -> a($newsco); //继承标签内容
$root -> a($index); //继承子类
$doc -> a($root);
$doc -> save(“php100.xml”); // 生成保存为XML
以下我做的未例
<?php
$mybooks = array();
$mybooks [] = array(
'title' => "PHP Hacks",
'author' => "Jack Herrington",
'publisher' => "Reilly"
$mybooks [] = array(
'title' => "a",
'author' => "aa",
'publisher' => "aaa"
$mybooks [] = array(
'title' => "b",
'author' => "bb",
'publisher' => "bbb"
$doc = new DOMDocument('1.0', 'utf-8'); // 声明版本和编码
$doc -> formatOutput = true; $root = $doc -> createElement_x_x('root');
foreach($mybooks as $key=> $book){
$key++;
$books = $doc -> createElement_x_x('books'); //创建一个标签
$tit = $doc -> createElement_x_x('title'); //创建一个标签
$auth = $doc -> createElement_x_x('author'); //创建一个标签
$publi = $doc -> createElement_x_x('publisher'); $id = $doc -> createAttribute('id'); //创建一个属性
$newsid = $doc -> createTextNode($key); //设置属性内容
$title = $doc -> createTextNode($book['title']); //设置标签内容
$author = $doc -> createTextNode($book['author']); //设置标签内容
$publisher = $doc -> createTextNode($book['publisher']); $id -> a($newsid);
$tit -> a($title);
$auth -> a($author);
$publi -> a($publisher); $books -> a($id); //继承属性内容
$books -> a($tit); //继承标签内容
$books -> a($auth); //继承标签内容
$books -> a($publi); $root
}
//继承子类
$doc -> a($root);
$doc -> save("books.xml");
?>