phpxml数据编写 php如何创建xml文件

怎样通过php程序返回xml格式的数据无论是返回json 还是 xml 数据phpxml数据编写,区别仅在于数据phpxml数据编写的格式 。
返回 xml 格式数据示例如下phpxml数据编写:
?php
//指示返回数据格式为 xml
header('Content-Type: text/xml');
?
?xml version="1.0" encoding="utf-8" ?
?php
//构造 xml
//$xmldata = "https://www.04ip.com/post/
//data
//site_name$site[name]/site_name
//........
//data";
echo $xmldata;
?
php生成xml代码快说把使用PHP DOMDocument创建动态XML文件
当处理基于XML应用程序时,开发者经常需要建立XML编码数据结构 。例如,Web中基于用户输入的XML状态模板,服务器请求XML语句,以及基于运行时间参数的客户响应 。
尽管XML数据结构的构建比较费时 , 但如果使用成熟的PHP DOM应用程序接口,一切都会变得简单明了 。本文将向你介绍PHP DOM应用程序接口的主要功能,演示如何生成一个正确的XML完整文件并将其保存到磁盘中 。
创建文档类型声明
一般而言,XML声明放在文档顶部 。在PHP中声明十分简单:只需实例化一个DOM文档类的对象并赋予它一个版本号 。查看程序清单A:
程序清单 A
复制代码 代码如下:
?php
// create doctype
$dom = new DOMDocument("1.0");
// display document in browser as plain text
// display document in browser as plain text
// for readability purposes
header("Content-Type: text/plain");
// save and display tree
echo $dom-saveXML();
?
请注意DOM文档对象的saveXML()方法 。稍后我再详细介绍这一方法,现在你只需要简单认识到它用于输出XML文档的当前快照到一个文件或浏览器 。在本例,为增强可读性,我已经将ASCII码文本直接输出至浏览器 。在实际应用中,可将以text/XML头文件发送到浏览器 。
如在浏览器中查看输出,你可看到如下代码:
?xml version="1.0"?
添加元素和文本节点
XML真正强大的功能是来自其元素与封装的内容 。幸运的是,一旦你初始化DOM文档 , 很多操作变得很简单 。此过程包含如下两步骤:
对想添加的每一元素或文本节点 , 通过元素名或文本内容调用DOM文档对象的createElement()或createTextNode()方法 。这将创建对应于元素或文本节点的新对象 。
通过调用节点的appendChild()方法,并把其传递给上一步中创建的对象,并在XML文档树中将元素或文本节点添加到父节点 。
以下范例将清楚地演示这2步骤,请查看程序清单B 。
程序清单 B
复制代码 代码如下:
?php
// create doctype
$dom = new DOMDocument("1.0");
// display document in browser as plain text
// for readability purposes
header("Content-Type: text/plain");
// create root element
$root = $dom-createElement("toppings");
$dom-appendChild($root);
// create child element
$item = $dom-createElement("item");
$root-appendChild($item);
// create text node
$text = $dom-createTextNode("pepperoni");
$item-appendChild($text);
// save and display tree
echo $dom-saveXML();
?
这 里,我首先创建一个名字为toppings的根元素,并使它归于XML头文件中 。然后,我建立名为item的元素并使它 归于根元素 。最后,我又创建一个值为“pepperoni”的文本节点并使它归于item元素 。最终结果如下:
复制代码 代码如下:
?xml version="1.0"?
toppings
itempepperoni/item
/toppings
如果你想添加另外一个topping,只需创建另外一个item并添加不同的内容,如程序清单C所示 。
程序清单C
复制代码 代码如下:
?php
// create doctype
$dom = new DOMDocument("1.0");
// display document in browser as plain text
// for readability purposes
header("Content-Type: text/plain");
// create root element
$root = $dom-createElement("toppings");
$dom-appendChild($root);
// create child element
$item = $dom-createElement("item");
$root-appendChild($item);
// create text node
$text = $dom-createTextNode("pepperoni");
$item-appendChild($text);
// create child element
$item = $dom-createElement("item");
$root-appendChild($item);
// create another text node
$text = $dom-createTextNode("tomato");
$item-appendChild($text);
// save and display tree
echo $dom-saveXML();
?
以下是执行程序清单C后的输出:
复制代码 代码如下:
?xml version="1.0"?
toppings
itempepperoni/item
itemtomato/item
/toppings
添加属性
通过使用属性,你也可以添加适合的信息到元素 。对于PHP DOM API , 添加属性需要两步:首先用DOM文档对象的createAttribute()方法创建拥有此属性名字的节点,然后将文档节点添加到拥有属性值的属性节点 。详见程序清单D 。
程序清单 D
复制代码 代码如下:
?php
// create doctype
$dom = new DOMDocument("1.0");
// display document in browser as plain text
// for readability purposes
header("Content-Type: text/plain");
// create root element
$root = $dom-createElement("toppings");
$dom-appendChild($root);
// create child element
$item = $dom-createElement("item");
$root-appendChild($item);
// create text node
$text = $dom-createTextNode("pepperoni");
$item-appendChild($text);
// create attribute node
$price = $dom-createAttribute("price");
$item-appendChild($price);
// create attribute value node
$priceValue = https://www.04ip.com/post/$dom-createTextNode("4");
$price-appendChild($priceValue);
// save and display tree
echo $dom-saveXML();
?
输出如下所示:
复制代码 代码如下:
?xml version="1.0"?
toppings
item price="4"pepperoni/item
/toppings
添加CDATA模块和过程向导
虽然不经常使用CDATA模块和过程向导,但是通过调用DOM文档对象的createCDATASection()和createProcessingInstruction()方法, PHP API 也能很好地支持CDATA和过程向导 , 请见程序清单E 。
程序清单 E
复制代码 代码如下:
?php
// create doctype
// create doctype
$dom = new DOMDocument("1.0");
// display document in browser as plain text
// for readability purposes
header("Content-Type: text/plain");
// create root element
$root = $dom-createElement("toppings");
$dom-appendChild($root);
// create child element
$item = $dom-createElement("item");
$root-appendChild($item);
// create text node
$text = $dom-createTextNode("pepperoni");
$item-appendChild($text);
// create attribute node
$price = $dom-createAttribute("price");
$item-appendChild($price);
// create attribute value node
$priceValue = https://www.04ip.com/post/$dom-createTextNode("4");
$price-appendChild($priceValue);
// create CDATA section
$cdata = https://www.04ip.com/post/$dom-createCDATASection(" Customer requests that pizza be sliced into 16 square pieces ");
$root-appendChild($cdata);
// create PI
$pi = $dom-createProcessingInstruction("pizza", "bake()");
$root-appendChild($pi);
// save and display tree
echo $dom-saveXML();
?
输出如下所示:
复制代码 代码如下:
?xml version="1.0"?
toppings
item price="4"pepperoni/item
![CDATA[
Customer requests that pizza be sliced into 16 square pieces
]]
?pizza bake()?
/toppings
保存结果
一旦已经实现你的目标,就可以将结果保存在一个文件或存储于PHP的变量 。通过调用带有文件名的save()方法可以将结果保存在文件中 , 而通过调用saveXML()方法可存储于PHP的变量 。请参考以下实例(程序清单F):
程序清单 F
复制代码 代码如下:
?php
// create doctype
$dom = new DOMDocument("1.0");
// create root element
$root = $dom-createElement("toppings");
$dom-appendChild($root);
$dom-formatOutput=true;
// create child element
$item = $dom-createElement("item");
$root-appendChild($item);
// create text node
$text = $dom-createTextNode("pepperoni");
$item-appendChild($text);
// create attribute node
$price = $dom-createAttribute("price");
$item-appendChild($price);
// create attribute value node
$priceValue = https://www.04ip.com/post/$dom-createTextNode("4");
$price-appendChild($priceValue);
// create CDATA section
$cdata = https://www.04ip.com/post/$dom-createCDATASection(" Customer requests that pizza be
sliced into 16 square pieces ");
$root-appendChild($cdata);
// create PI
$pi = $dom-createProcessingInstruction("pizza", "bake()");
$root-appendChild($pi);
// save tree to file
$dom-save("order.xml");
// save tree to string
$order = $dom-save("order.xml");
?
下面是实际的例子,大家可以测试下 。
xml.php(生成xml)
复制代码 代码如下:
?
$conn = mysql_connect('localhost', 'root', '123456') or die('Could not connect: ' . mysql_error());
mysql_select_db('vdigital', $conn) or die ('Can\'t use database : ' . mysql_error());
$str = "SELECT id,username FROM `admin` GROUP BY `id` ORDER BY `id` ASC";
$result = mysql_query($str) or die("Invalid query: " . mysql_error());
if($result)
{
$xmlDoc = new DOMDocument();
if(!file_exists("01.xml")){
$xmlstr = "?xml version='1.0' encoding='utf-8' ?message/message";
$xmlDoc-loadXML($xmlstr);
$xmlDoc-save("01.xml");
}
else { $xmlDoc-load("01.xml");}
$Root = $xmlDoc-documentElement;
while ($arr = mysql_fetch_array($result)){
$node1 = $xmlDoc-createElement("id");
$text = $xmlDoc-createTextNode(iconv("GB2312","UTF-8",$arr["id"]));
$node1-appendChild($text);
$node2 = $xmlDoc-createElement("name");
$text2 = $xmlDoc-createTextNode(iconv("GB2312","UTF-8",$arr["username"]));
$node2-appendChild($text2);
$Root-appendChild($node1);
$Root-appendChild($node2);
$xmlDoc-save("01.xml");
}
}
mysql_close($conn);
?
test.php(应用测试)
复制代码 代码如下:
?
$xmlDoc = new DOMDocument();
$xmlDoc-load("");
$x=$xmlDoc-getElementsByTagName('name');
for ($i=0; $i=$x-length-1; $i)
{
if(strpos($x-item($i)-nodeValue,"fang")!==false)
{
echo $x-item($i)-parentNode-childNodes-item(1)-nodeValue;
}
}
?
PHP生成和获取XML格式数据 在做数据接口时 我们通常要获取第三方数据接口或者给第三方提供数据接口 而这些数据格式通常是以XML或者JSON格式传输 本文将介绍如何使用PHP生成XML格式数据供第三方调用以及如何获取第三方提供的XML数据
生成XML格式数据
我们假设系统中有一张学生信息表student 需要提供给第三方调用 并有id name sex age分别记录学生的姓名 性别 年龄等信息
CREATE TABLE `student` (
`id` int( ) NOT NULL auto_increment
`name` varchar( ) NOT NULL
`sex` varchar( ) NOT NULL
`age` *** allint( ) NOT NULL default
PRIMARY KEY(`id`)
) ENGINE=MyISAMDEFAULT CHARSET=utf ;
首先 建立createXML php文件 先连接数据库 获取数据
include_once ( connect php ) //连接数据库
$sql = select * from student ;
$result = mysql_query($sql) or die( Invalid query: mysql_error())
while ($row = mysql_fetch_array($result)) {
$arr[] = array(
name = $row[ name ]
sex = $row[ sex ]
age = $row[ age ]

}
这个时候 数据就保存在$arr中 你可以使用print_r打印下数据测试
接着 建立xml 循环数组 将数据写入到xml对应的节点中
$doc = new DOMDocument( utf )// 声明版本和编码
$doc formatOutput = true;
$r = $doc createElement( root )
$doc appendChild($r)
foreach ($arr as $dat) {
$b = $doc createElement( data )
$name = $doc createElement( name )
$name appendChild($doc createTextNode($dat[ name ]))
$b appendChild($name)
$sex = $doc createElement( sex )
$sex appendChild($doc createTextNode($dat[ sex ]))
$b appendChild($sex)
$age = $doc createElement( age )
$age appendChild($doc createTextNode($dat[ age ]))
$b appendChild($age)
$r appendChild($b)
}
echo $doc saveXML()
我们调用了PHP内置的类DOMDocument来处理与生成xml 最终生成的xml格式请点击这里看效果
【phpxml数据编写 php如何创建xml文件】 ?xml version= encoding= utf ?
root
data
name李王皓/name
sex男/sex
age /age
/data

/root
获取XML格式数据
现在我们假设要从第三方获取学生信息 数据格式是XML 我们需要使用PHP解析XML 然后将解析后的数据显示或者写入本地数据库 而这里关键的一步是解析XML
PHP有很多中方法可以解析XML 其中PHP提供了内置的XMLReader类可以循序地浏览过xml档案的节点 你可以想像成游标走过整份文件的节点 并抓取需要的内容 使用XMLReader是高效的 尤其是读取非常大的xml数据 相对其他方法 使用XMLReader消耗内存非常少
header( Content type:text/; Charset=utf )
$url = // helloweba /demo/importXML/createXML php ;
$reader = new XMLReader()//实例化XMLReader
$reader open($url) //获取xml
$i= ;
while ($reader read()) {
if ($reader nodeType == XMLReader::TEXT) { //判断node类型
$m = $i% ;
if($m== )
$name = $reader value;//读取node值
if($m== )
$sex = $reader value;
if($m== ){
$age = $reader value;
$arr[] = array(
name = $name
sex = $sex
age = $age

}
$i;
}
}
//print_r($arr)
lishixinzhi/Article/program/PHP/201311/21636
PHP 读取和编写 XML什么是
XMLphpxml数据编写?
XML
是一种数据存储格式 。它没有定义保存什么数据,也没有定义数据的格式 。XML
只是定义phpxml数据编写了标记和这些标记的属性 。格式良好的
XML
标记看起来像这样:
复制代码
代码如下:
nameJack
Herrington/name
DOM读取
XML
复制代码
代码如下:
?php
$doc
=
new
DOMDocument();
$doc-load(
'books.xml'
);
$books
=
$doc-getElementsByTagName(
"book"
);
foreach(
$books
as
$book
)
{
$authors
=
$book-getElementsByTagName(
"author"
);
$author
=
$authors-item(0)-nodeValue;
$publishers
=
$book-getElementsByTagName(
"publisher"
);
$publisher
=
$publishers-item(0)-nodeValue;
$titles
=
$book-getElementsByTagName(
"title"
);
$title
=
$titles-item(0)-nodeValue;
echo
"$title
-
$author
-
$publisher\n";
}
?

DOM
编写
XML
复制代码
代码如下:
?php
$books
=
array();
$books
[]
=
array(
'title'
=
'PHP
Hacks',
'author'
=
'Jack
Herrington',
);
$doc
=
new
DOMDocument();
//创建dom对象
$doc-formatOutput
=
true;
$r
=
$doc-createElement(
"books"
);//创建标签
$doc-appendChild(
$r
);
//将$r标签,加入到xml格式中 。
foreach(
$books
as
$book
)
{
$b
=
$doc-createElement(
"book"
);
//创建标签
$author
=
$doc-createElement(
"author"
);
$author-appendChild($doc-createTextNode(
$book['author']
));
//给标签添加内容
$b-appendChild(
$author
);
//将子标签
加入父标签
$r-appendChild(
$b
);
//加入父标签中!
}
echo
$doc-saveXML();
?
以上就是这2段读取和编写XML的DOM代码了,小伙伴们了解了没 , 有什么疑问可以给phpxml数据编写我留言
如何通过PHP生成和获取XML格式数据1自己拼phpxml数据编写,XML编码
?php
header('Content-type:text/xml');
echo "?xml version='1.0' encoding='utf-8'";
echo "book";
echo "PHP";
echo "namePHP程序开发范例宝典/name";
echo "price 单位='元/本'89.00/price";
echo "date2007-09-01/date";
echo "/PHP";
echo "/book";
?
拼接phpxml数据编写的效果
2从数据库中查询再拼XML编码
?php
$dsn="mysql:host=localhost;dbname=test";
try {
$pdo = new PDO($dsn,'root','passwowd'); //初始化一个PDO对象phpxml数据编写,就是创建phpxml数据编写了数据库连接对象$pdo
$query="select * from book";//定义SQL语句
$pdo-query('set names utf8');
$result=$pdo-prepare($query); //准备查询语句
$result-execute();//执行查询语句 , 并返回结果集
$arr='';
while($res=$result-fetch()){
$arr.='PHPid'.$res[0].'/idname'.$res[1].'/namedate'.$res[2].'/date'.'price'.$res[3].'/price/PHP';
}
echo "?xml version='1.0' encoding='utf-8'?book".$arr.'/book';
} catch (PDOException $e) {
die ("Error!: ".$e-getMessage()."br");
}
?
拼接phpxml数据编写的效果
3使用ajax获取 , DOM解析
!DOCTYPE html
html lang="en"
head
meta charset="UTF-8"
titlexml/title
/head
body
script
function check(){
var xhr=new XMLHttpRequest();
xhr.open('GET','xml.php');
xhr.onreadystatechange=function(){
if(xhr.readyState==4xhr.status==200){
console.log(xhr.responseText);
//初始化 DOM解析对象
var domParser = new DOMParser();
//字符串解码为对象
var xmlDoc = domParser.parseFromString(xhr.responseText,'text/xml');
//按标签名获取元素 返回数组
var elements = xmlDoc.getElementsByTagName('PHP');
//拼接html格式字符串
var str ='trthid/ththname/ththdate/ththprice/th/tr';
for (var i=0;ielements.length;i){
var id=elements[i].getElementsByTagName('id')[0].firstChild.nodeValue;
var name=elements[i].getElementsByTagName('name')[0].firstChild.nodeValue;
var date=elements[i].getElementsByTagName('date')[0].firstChild.nodeValue;
var price=elements[i].getElementsByTagName('price')[0].firstChild.nodeValue;
str = 'trtd' id '/tdtd' name '/tdtd' date '/tdtd' price '/td/tr';
}
document.getElementById('table2').innerHTML=str;
}
};
xhr.send(null);
}
/script
button onclick="check();"点我/button
table id="table2" border="2" cellspacing="0"
/table
/body
/html
效果
1
2
补充:
使用JSON
1数据库查询,自己拼 JSON 编码
?php
$dsn="mysql:host=localhost;dbname=test";
try {
$pdo = new PDO($dsn,'root','password'); //初始化一个PDO对象,就是创建了数据库连接对象$pdo
$query="select * from book";//定义SQL语句
$pdo-query('set names utf8');
$result=$pdo-prepare($query); //准备查询语句
$result-execute();//执行查询语句,并返回结果集
$a=$arr='';
while($res=$result-fetch()){
$arr.='{"id":'.'"'.$res[0].'",'.'"name":'.'"'.$res[1].'",'.'"time":'.'"'.$res[2].'",'.'"jia":'.'"'.$res[3].'",'.'"zhe":'.'"'.$res[4].'",'.'"chu":'.'"'.$res[5].'"},';
}
echo $a="[".substr($arr,0,strlen($arr)-1)."]";
} catch (PDOException $e) {
die ("Error!: ".$e-getMessage()."br");
}
?
2数据库查询,函数 JSON 编码
?php
$dsn="mysql:host=localhost;dbname=test";
try {
$pdo = new PDO($dsn,'root','password'); //初始化一个PDO对象,就是创建了数据库连接对象$pdo
$query="select * from book";//定义SQL语句
$pdo-query('set names utf8');
$result=$pdo-prepare($query); //准备查询语句
$result-execute();//执行查询语句,并返回结果集
$res=$result-fetchAll();
//JSON 编码
echo json_encode($res);
} catch (PDOException $e) {
die ("Error!: ".$e-getMessage()."br/");
}
?
效果
3ajax获?。?JSON解析
!DOCTYPE html
html lang="en"
head
meta charset="UTF-8"
titleJSON/title
/head
body
script
function check() {
var XHR = new XMLHttpRequest();
XHR.open('GET','JSON.php');
XHR.onreadystatechange = function (){
if(XHR.readyState == 4XHR.status ==200){
var books =JSON .parse(XHR.responseText);
var books2='trthid/ththbookname/ththtime/ththprice/ththmarker/ththpublisher/th/tr'
for (var i=0;ibooks.length;i){
books2 = 'trtd' (books[i ].id) '/tdtd' (books[i ].name) '/tdtd' (books[i ].time) '/tdtd' (books[i ].jia) '/tdtd' (books[i ].zhe) '/tdtd' (books[i ].chu) '/td/tr';
}
document.getElementById('table2').innerHTML=books2;
}
};
XHR.send(null);
}
/script
input type="button" value="https://www.04ip.com/post/点我" onclick="check();"
table id="table2" border="2" cellspacing="0"/table
/body
/html
php输出xml文件应该如何写最简单的办法就是拼凑:
echo '?xml version="1.0" encoding="utf-8" ?';
echo 'skplyaer';
ech ...
echo '/ckplayer';
关于phpxml数据编写和php如何创建xml文件的介绍到此就结束了,不知道你从中找到你需要的信息了吗 ?如果你还想了解更多这方面的信息,记得收藏关注本站 。

    推荐阅读