php+xml中SimpleXML的应用实例

本篇内容主要讲解“php+xml中SimpleXML的应用实例”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“php+xml中SimpleXML的应用实例”吧!

SimpleXML的核心思想:以面向对象的方式来操作xml文件,它会将xml文件的所有元素都转成对象。

xml文档:words.xml

复制代码 代码如下:

<?xml version="1.0" encoding="utf-8"?>
<words>
<word>
 <en>boy</en>
 <ch>男孩</ch>
</word>
<word>
 <en>girl</en>
 <ch>女孩</ch>
</word>
<word>
 <en>teacher</en>
 <ch>老师</ch>
</word>
<word>
 <en>beauty</en>
 <ch>美女</ch>
</word>
</words>


simplexml使用实例:

复制代码 代码如下:

<?php
echo "<pre>";
$words = simplexml_load_file("words.xml");//返回数组对象,可以用print_r()或var_dump()查看
var_dump($words);
?>

读取内容:

复制代码 代码如下:

<?php
echo "<pre>";
$words = simplexml_load_file("words.xml");//返回数组对象,可以用print_r()或var_dump()查看
//echo $words->word[2];
foreach($words->word as $row){//$row还是一个对象
 print_r($row);
 echo $row->ch."<hr>"; //其实,$row->ch还是一个对象,只不能它能echo出来
}
?>


第二段代码输出结果:

复制代码 代码如下:

SimpleXMLElement Object
(
    [en] => boy
    [ch] => 男孩
)
男孩
SimpleXMLElement Object
(
    [en] => girl
    [ch] => 女孩
)
女孩
SimpleXMLElement Object
(
    [en] => teacher
    [ch] => 老师
)
老师

到此,相信大家对“php+xml中SimpleXML的应用实例”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!