php写xml, 赋值由数组怎么弄

jellday 2008-12-03 09:08:05
<?php

//Creates XML string and XML document using the DOM
$dom = new DomDocument('1.0');

//add root - <books>
$books = $dom->appendChild($dom->createElement('books'));

//add <book> element to <books>
$book = $books->appendChild($dom->createElement('book'));

//add <title> element to <book>
$title = $book->appendChild($dom->createElement('title'));

//add <title> text node element to <title>
$title->appendChild($dom->createTextNode('Great American
Novel'));

//generate xml
$dom->formatOutput = true; // set the formatOutput attribute of
domDocument to true
// save XML as string or file
$test1 = $dom->saveXML(); // put string in test1
$dom -> save('test1.xml'); // save as file
?>


输出文件

<?xml version="1.0"?>
<books>
<book>
<title>Great American Novel</title>
</book>
</books>



如果title的值由$lw[0]['title']得到,应该怎么弄啊?
...全文
166 点赞 收藏 3
写回复
3 条回复
切换为时间正序
当前发帖距今超过3年,不再开放新的回复
发表回复
cyxin2121921 2008-12-05
mark
回复
jellday 2008-12-04
非常感谢!

有个问题, 如果数组的编码为gb2312, 我得到错误

Warning: DOMDocument::saveXML() [domdocument.savexml]: string is not in UTF-8 in C:\PHPnow\htdocs\test.php on line 48

Warning: DOMDocument::saveXML() [domdocument.savexml]: string is not in UTF-8 in C:\PHPnow\htdocs\test.php on line 48

Warning: DOMDocument::saveXML() [domdocument.savexml]: string is not in UTF-8 in C:\PHPnow\htdocs\test.php on line 48

Warning: DOMDocument::save() [domdocument.save]: string is not in UTF-8 in C:\PHPnow\htdocs\test.php on line 49

Warning: DOMDocument::save() [domdocument.save]: string is not in UTF-8 in C:\PHPnow\htdocs\test.php on line 49

Warning: DOMDocument::save() [domdocument.save]: string is not in UTF-8 in C:\PHPnow\htdocs\test.php on line 49

是不是要指定xml编码为gb2312呢? 如何指定?
回复
dubiousway 2008-12-03
//这样对吗?

<?php

$lw= array(array('title'=>"Love Story"));

//Creates XML string and XML document using the DOM
$dom = new DomDocument('1.0');

//add root - <books>
$books = $dom->appendChild($dom->createElement('books'));

//add <book> element to <books>
$book = $books->appendChild($dom->createElement('book'));

//add <title> element to <book>
$title = $book->appendChild($dom->createElement('title'));

//add <title> text node element to <title>

$title->appendChild($dom->createTextNode($lw[0]['title']));

//generate xml
$dom->formatOutput = true; // set the formatOutput attribute of domDocument to true
// save XML as string or file
$test1 = $dom->saveXML(); // put string in test1
$dom -> save('test1.xml'); // save as file
?>

回复
相关推荐
发帖
基础编程
创建于2007-09-28

2.1w+

社区成员

从PHP安装配置,PHP入门,PHP基础到PHP应用
申请成为版主
帖子事件
创建了帖子
2008-12-03 09:08
社区公告
暂无公告