|
該文舉一個使用php中的dom生成xml文件的簡單例子。假如需要生成一個描述某些博文的xml文件,可以使用下述代碼來生成: //定義博文數(shù)據(jù),實際數(shù)據(jù)應(yīng)該從數(shù)據(jù)庫中取出
$articles = array(array('title' => '深入淺出CURL', 'author' => '360weboy'),
array('title' => '深入理解execution context', 'author' => 'jack.yin'));
//構(gòu)建dom document
$xml = new DOMDocument();
//格式化輸出
$xml->formatOutput = TRUE;
//設(shè)置xml文檔的編碼為utf8
$xml->encoding = 'utf8';
//構(gòu)建文章根節(jié)點
$root = $xml->createElement('articles');
if (count($articles) > 0)
{
//遍歷數(shù)組,生成文章子節(jié)點
foreach($articles as $article)
{
//建立文章節(jié)點
$a = $xml->createElement('article');
//建立title字節(jié)點
$title = $xml->createElement('title');
//建立文本節(jié)點,并且加入到title節(jié)點下
$title->appendChild($xml->createTextNode($article['title']));
//添加title節(jié)點到article節(jié)點下
$a->appendChild($title);
$author = $xml->createElement('author');
$author->appendChild($xml->createTextNode($article['author']));
$a->appendChild($author);
//添加article節(jié)點到根節(jié)點下
$root->appendChild($a);
}
}
//添加根節(jié)點到xml文檔下
$xml->appendChild($root);
//設(shè)置charset為utf-8,不然瀏覽器會顯示中文為亂碼
header('Content-Type: text/html;charset=UTF-8');
//保存xml文檔到artciles.xml
if ($xml->save('articles.xml') !== FALSE)
{
echo 'articles.xml已經(jīng)生成保存!';
}
else
{
echo 'articles.xml生成失敗';
}
上述代碼生成的xml文檔如下: <?xml version="1.0"?>
<articles>
<article>
<title><![CDATA[深入淺出CURL]]></title>
<author>360weboy</author>
</article>
<article>
<title><![CDATA[深入理解execution context]]></title>
<author>jack.yin</author>
</article>
</articles>
總結(jié): 當然,讀取xml文檔的方式也差不多。使用dom來處理一些小型xml文檔還是比較不錯的,如果你熟悉javascript的話,相信dom這種方式對你來說還是很好理解的。但是,由于使用這種方式的話,php需要將這個文檔讀入內(nèi)存中,構(gòu)建一顆dom樹,所以,如果處理大型xml文檔的話,是不太合適的,因為太消耗內(nèi)存了! 其它方法請參考手冊 – http:///manual/en/class.domdocument.php |
|
|
來自: 明天網(wǎng)吧 > 《xml》