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']得到,应该怎么弄啊?
...全文
212 3 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
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
?>

21,890

社区成员

发帖
与我相关
我的任务
社区描述
从PHP安装配置,PHP入门,PHP基础到PHP应用
社区管理员
  • 基础编程社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧