php中simplexml_load_file函数用法实例
本文实例讲述了php中simplexml_load_file函数用法。分享给大家供大家参考。具体用法分析如下:
在php中simplexml_load_file()函数把XML文档载入对象中之后我们就可以利用由此函数返回的对象进行相关的操作了,下面我们看几个测试实例.
例子,XML文件代码如下:
<?xmlversion="1.0"encoding="ISO-8859-1"?> <note> <to>George</to> <from>John</from> <heading>Reminder</heading> <body>Don'tforgetthemeeting!</body> </note>
PHP代码如下:
<?php
if(file_exists('test.xml'))
{
$xml=simplexml_load_file('test.xml');
var_dump($xml);
}
else
{
exit('Error.');
}
?>运行输出结果如下:
object(SimpleXMLElement)#1(4){
["to"]=>
string(6)"George"
["from"]=>
string(4)"John"
["heading"]=>
string(8)"Reminder"
["body"]=>
string(25)"Don'tforgetthemeeting!"
}
假如有一个“iciba.xml”文件,其内容如下:
<?xmlversion="1.0"encoding="UTF-8"?> <dictnum="219"id="219"name="219"> <key>天空</key> <pos></pos> <acceptation>Array;Array;</acceptation> <sent> <orig>Thechurchtowerstoodagainsttheskylikeafingerpointingtowardsheaven.</orig> <trans>教堂的尖塔在天空的映衬下宛如指向天空的手指。</trans> </sent> <sent> <orig>Aballoonfloatedacrossthesky.</orig> <trans>气球飘过天空。</trans> </sent> <sent> <orig>Aboltoflightninglitupthesky.</orig> <trans>(一道)闪电照亮了天空。</trans> </sent> <sent> <orig>Abrightmovingobjectappearedintheskyatsunset.</orig> <trans>日落西山时,天空出现了一个移动的发亮物体。</trans> </sent> <sent> <orig>Abrightrainbowarchedabove.</orig> <trans>一弯明亮的彩虹悬挂在天空。</trans> </sent> </dict>
在PHP语言中我们可以用以下方法取得我们想要的值:
<?php
$xmldata=simplexml_load_file("iciba.xml");
header("Content-Type:text/html;charset=UTF-8");
print_r($xmldata);//第一部分
$listcount=count($xmldata->sent);
for($i=0;$i<$listcount;$i++){//第二部分
$dictlist=$xmldata->sent[$i];
echo"<br/>例句:".$dictlist->orig;
echo"<br/>翻译:".$dictlist->trans;
}
?>
“第一部分”将输出:
SimpleXMLElementObject
(
[@attributes]=>Array
(
[num]=>219
[id]=>219
[name]=>219
)
[key]=>天空 [pos]=>SimpleXMLElementObject ( )
[acceptation]=>Array;Array; [sent]=>Array ( [0]=>SimpleXMLElementObject ( [orig]=>Thechurchtowerstoodagainsttheskylikeafingerpointingtowardsheaven. [trans]=>教堂的尖塔在天空的映衬下宛如指向天空的手指。 )
[1]=>SimpleXMLElementObject ( [orig]=>Aballoonfloatedacrossthesky. [trans]=>气球飘过天空。 )
[2]=>SimpleXMLElementObject ( [orig]=>Aboltoflightninglitupthesky. [trans]=>(一道)闪电照亮了天空。 )
[3]=>SimpleXMLElementObject ( [orig]=>Abrightmovingobjectappearedintheskyatsunset. [trans]=>日落西山时,天空出现了一个移动的发亮物体。 )
[4]=>SimpleXMLElementObject ( [orig]=>Abrightrainbowarchedabove. [trans]=>一弯明亮的彩虹悬挂在天空。 )
)
)