這篇文章主要介紹了PHP輸出XML格式資料的方法,結合實例形式總結分析了php常用的xml格式資料輸出相關操作技巧,需要的朋友可以參考下
本文實例講述了PHP輸出XML格式資料的方法。分享給大家參考,如下:
方法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>"; ?>
上述範例運作效果圖如下:
<?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>"; ?>
<?php header('Content-Type: text/xml;'); //创建新的xml文件 $dom = new DOMDocument('1.0', 'utf-8'); //建立<response>元素 $response = $dom->createElement('response'); $dom->a($response); //建立<books>元素并将其作为<response>的子元素 $books = $dom->createElement('books'); $response->a($books); //为book创建标题 $title = $dom->createElement('title'); $titleText = $dom->createTextNode('PHP与AJAX'); $title->a($titleText); //为book创建isbn元素 $isbn = $dom->createElement('isbn'); $isbnText = $dom->createTextNode('1-21258986'); $isbn->a($isbnText); //创建book元素 $book = $dom->createElement('book'); $book->a($title); $book->a($isbn); //将<book>作为<books>子元素 $books->a($book); //在一字符串变量中建立XML结构 $xmlString = $dom->saveXML(); //输出XML字符串 echo $xmlString; ?>