您的位置:首页 > 编程语言 > PHP开发

php中simplexml_load_file函数的学习

2016-11-16 22:32 645 查看
php中把xm文件转换为以一个对象,可以使用simplexml_load_file来实现,首先创建一个xml文件为test.xml(文件最好是使用utf-8格式来保存),内容为

<?xml version="1.0" encoding="UTF-8" ?>
<themeeditor>

<author>test</author>
<name>testname</name>
<layout>

<item>
<block>整体布局</block>
<default>fullwidth</default>
<option>
<text>宽屏</text>
<value>fullwidth</value>
</option>
<option>
<text>中屏</text>
<value>boxed-lg</value>
</option>
<option>
<text>小屏</text>
<value>boxed-md</value>
</option>
</item>

<item>
<block>浏览</block>
<default>0</default>
<option>
<text>启用</text>
<value>1</value>
</option>
<option>
<text>关闭</text>
<value>0</value>
</option>
</item>
</layout>
</themeeditor>


接下来就是使用php来转换了,代码如下:

$out = simplexml_load_file('test.xml' );
var_dump($out);


得到的输出结果为:

object(SimpleXMLElement)#1 (3) { ["author"]=> string(4) "test" ["name"]=> string(8) "testname" ["layout"]=> object(SimpleXMLElement)#2 (1) { ["item"]=> array(2) { [0]=> object(SimpleXMLElement)#3 (3) { ["block"]=> string(12) "整体布局" ["default"]=> string(9) "fullwidth" ["option"]=> array(3) { [0]=> object(SimpleXMLElement)#5 (2) { ["text"]=> string(6) "宽屏" ["value"]=> string(9) "fullwidth" } [1]=> object(SimpleXMLElement)#6 (2) { ["text"]=> string(6) "中屏" ["value"]=> string(8) "boxed-lg" } [2]=> object(SimpleXMLElement)#7 (2) { ["text"]=> string(6) "小屏" ["value"]=> string(8) "boxed-md" } } } [1]=> object(SimpleXMLElement)#4 (3) { ["block"]=> string(6) "浏览" ["default"]=> string(1) "0" ["option"]=> array(2) { [0]=> object(SimpleXMLElement)#7 (2) { ["text"]=> string(6) "启用" ["value"]=> string(1) "1" } [1]=> object(SimpleXMLElement)#6 (2) { ["text"]=> string(6) "关闭" ["value"]=> string(1) "0" } } } } } }


note:simplexml_load_file可以使用第二个参数来返回一个自定义的一个类,但是这个类必须是SimpleXMLElement的子类

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: