Home  >  Article  >  php教程  >  php SimpleXML读写XML接口文件例子分析

php SimpleXML读写XML接口文件例子分析

WBOY
WBOYOriginal
2016-05-25 16:42:081476browse

php5中读写xml文档是非常方便的,我们可以使用php SimpleXML对话来帮我们快速解析与生成xml格式的文件.

创建一个SimpleXML对象有三种方法:

使用new关键字创建,代码如下:

$xml="1aaa16 
2bbb26"; 
$rss=new SimpleXMLElement($xml);
使用simplexml_load_string()创建,代码如下:
$xml="1aaa16 
2bbb26";//开源代码phprm.com 
$rss=simplexml_load_string($xml);
最常用的方法,使用simplexml_load_file()URL创建,代码如下:
$rss=simplexml_load_file("rss.xml");或
$rss=simplexml_load_file("/rss.xml");//远程文档

先看个例子,代码如下:

1aaa162bbb26"; 
$rss=new SimpleXMLElement($xml); 
foreach($rss->item as $v){ 
    echo $v->name,'
'; } echo $rss->item[1]->age;//读取数据 echo '
'; $rss->item[1]->name='ccc';//修改数据 foreach($rss->item as $v){ echo $v->name,'
';//aaa
ccc
} echo '
'; unset($rss->item[1]);//输出数据 foreach($rss->item as $k=>$v){ echo $v->name,'
';//aaa
} echo '
'; //添加数据 $item=$rss->addChild('item'); $item->addChild('id','3'); $item->addChild('name','ccc_new'); $item->addChild('age','40'); foreach($rss->item as $k=>$v){ echo $v->name,'
';//aaa
ccc_new
} $rss->asXML('personinfo.xml');

xml数据的读取:可以直接通过元素的名称来访问特定的元素,文档中的所有元素都被看成是该对象的属性,实例代码如下:

foreach($rss->item as $v){ 
    echo $v->name,' 
';//aaa
bbb
} echo $rss->item[1]->age;//26

xml数据修改,可以直接利用对象属性赋值的方法来直接编辑一个元素的内容,实例代码如下:

$rss->item[1]->name='ccc';//修改数据 
foreach($rss->item as $v){ 
    echo $v->name,' 
';//aaa
ccc
}

可以用php内容函数unset来将一个元素从树中删除,实例代码如下:

unset($rss->item[1]); 
foreach($rss->item as $v){ 
    echo $v->name,' 
';//a www.phprm.com aa
}

xml添加元素数据,可通过对象的addChild方法来实现,实例代码如下:

$item=$rss->addChild('item'); 
$item->addChild('id','3'); 
$item->addChild('name','ccc_new'); 
$item->addChild('age','40'); 
foreach($rss->item as $k=>$v){ 
    echo $v->name,' 
';//aaa
ccc_new
}

xml数据的存储:使用对象的asXML()方法

$rss->asXML('personinfo.xml');//将xml数据存储到personinfo.xml文件中.


本文地址:

转载随意,但请附上文章地址:-)

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn