本篇文章是对PHP输出XML到页面的3种方法进行了详细的分析介绍,需要的朋友参考下
第一种方法: 复制代码 代码如下: <?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;
?>
|