PHP在页面输出XML的方法.避免乱码.
一般都是编码的问题了.
PHP输出XML到页面的方式3种,记录一下:
1:
<?php header("Content-type: text/xml"); echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"; echo "<users>"; echo "<user>"; echo "<name>"; echo "小小菜鸟"; echo "</name>"; echo "<age>"; echo "24"; echo "</age>"; echo "<sex>"; echo "男"; echo "</sex>"; echo "</user>"; echo "<user>"; echo "<name>"; echo "艳艳"; echo "</name>"; echo "<age>"; echo "23"; echo "</age>"; echo "<sex>"; echo "女"; echo "</sex>"; echo "</user>"; echo "</users>"; ?>
2:
<?php header("Content-type: text/xml"); echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"; echo "<users><user><name>小小菜鸟</name><age>24</age><sex>男</sex></user><user><name>艳艳</name><age>23</age><sex>女</sex></user></users>"; ?>3:
<?php /* 用PHP的DOM控件来创建XML输出 设置输出内容的类型为xml */ header('Content-Type: text/xml;'); //创建新的xml文件 $dom = new DOMDocument('1.0', 'utf-8'); //建立<response>元素 $response = $dom->createElement('response'); $dom->appendChild($response); //建立<books>元素并将其作为<response>的子元素 $books = $dom->createElement('books'); $response->appendChild($books); //为book创建标题 $title = $dom->createElement('title'); $titleText = $dom->createTextNode('PHP与AJAX'); $title->appendChild($titleText); //为book创建isbn元素 $isbn = $dom->createElement('isbn'); $isbnText = $dom->createTextNode('1-21258986'); $isbn->appendChild($isbnText); //创建book元素 $book = $dom->createElement('book'); $book->appendChild($title); $book->appendChild($isbn); //将<book>作为<books>子元素 $books->appendChild($book); //在一字符串变量中建立XML结构 $xmlString = $dom->saveXML(); //输出XML字符串 echo $xmlString; ?>
相关推荐
与卿画眉共浮生 2020-10-14
xiyang 2020-08-21
baijinswpu 2020-07-29
leonranri 2020-07-26
zhongliwen 2020-07-05
麋鹿麋鹿迷了路 2020-07-05
zengyu00 2020-07-05
XGQ 2020-07-04
CoderBoy 2020-06-28
whbing 2020-06-28
绝望的乐园 2020-06-27
wellfly 2020-06-26
菇星獨行 2020-06-25
草原孤狼 2020-06-25
坚持着执着 2020-06-16
wcqwcq 2020-06-14
yuanye0 2020-06-14
zhongliwen 2020-06-13
MrFuWen 2020-06-09