PHP xml解析与生成之SimpleXML使用介绍

巴扎黑
Release: 2023-03-15 07:36:01
original
1671 people have browsed it

xml就不多解释了,php也提供了操作xml的方法,php操作xml可以有多种方式如domdocment,simplexml,xmlwriter等其中最简单的应该是simplexml了,这次就来说说simplexml怎么读取和解析xml文件或字符串

1. 生成xml字符串和文件


');
 $item=$xml->addchild("item");
 $item->addchild("name","冯绍峰");
 $item->addchild("age","30");
 $item2=$xml->addchild("item");
 $item2->addchild("name","潘玮柏");
 $item2->addchild("age","29");
 $item2->addAttribute("id","02");
 header("Content-type: text/xml");
 echo $xml->asXml();
 $xml->asXml("student.xml");
?>
Copy after login

生成xml最重要的就是addchild,addAttribute,asXml三个方法,如果只是单纯生成xml文件的话那个header可以不要,下面是浏览器的显示结果

是不是很简单呢

2. simplexml解析xml文件或字符串


children());$i++){
   foreach ($xml->children()[$i] as $key => $value ) {
    echo "$key:$value"."
"; } } ?>
Copy after login

上面的方法适合解析xml文件,如果是xml字符串就把simplexml_load_file改为simplexml_load_string就可以了,children用于取得根节点或者子节点,取得的节点是一个数组直接遍历必要的时候加上过滤条件就可以了,下面是解析的结果

顺便把我的xml文件贴出来




 
   潘玮柏
   
上海市浦东新区
快乐崇拜
蔡依林
上海市徐汇区
独占神话
Copy after login

总的说来操作真的太简洁了。

The above is the detailed content of PHP xml解析与生成之SimpleXML使用介绍. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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 [email protected]
Latest issues
Popular Tutorials
More>
Latest downloads
More>
web effects
Website source code
Website materials
Front end template
About us Disclaimer Sitemap
PHP Chinese website:Public welfare online PHP training,Help PHP learners grow quickly!