第一種方法:
復制代碼 代碼如下:
<?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
/*
用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;
?>