微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

php中simplexml_load_file函数用法实例

本文实例讲述了PHP中simplexml_load_file函数用法分享给大家供大家参考。具体用法分析如下:

PHP中simplexml_load_file() 函数把 XML 文档载入对象中之后我们就可以利用由此函数返回的对象进行相关的操作了,下面我们看几个测试实例.

例子,XML文件代码如下:

代码如下:
George John Reminder Don't forget the meeting!
PHP 代码如下:
代码如下:

运行输出结果如下:
<div class="codetitle"><a style="CURSOR: pointer" data="42726" class="copybut" id="copybut42726" onclick="doCopy('code42726')"> 代码如下:

<div class="codebody" id="code42726">
object(SimpleXMLElement)#1 (4) {
["to"]=>
string(6) "George"
["from"]=>
string(4) "John"
["heading"]=>
string(8) "Reminder"
["body"]=>
string(25) "Don't forget the meeting!"
}

假如有一个“iciba.xml”文件,其内容如下:
代码如下:
天空 Array;Array; The church tower stood against the sky like a finger pointing towards heaven. 教堂的尖塔在天空的映衬下宛如指向天空的手指。 A balloon floated across the sky. 气球飘过天空。 A bolt of lightning lit up the sky. (一道)闪电照亮了天空。 A bright moving object appeared in the sky at sunset. 日落西山时,天空出现了一个移动的发亮物体。 A bright rainbow arched above. 一弯明亮的彩虹悬挂在天空。
在PHP语言中我们可以用以下方法取得我们想要的值:
代码如下:
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 "
例句:".$dictlist->orig;
echo "
翻译:".$dictlist->trans;
}
?>

“第一部分”将输出

代码如下:
Array ( [num] => 219 [id] => 219 [name] => 219 )

[key] => 天空 [pos] => SimpleXMLElement Object ( )

[acceptation] => Array;Array; [sent] => Array ( [0] => SimpleXMLElement Object ( [orig] => The church tower stood against the sky like a finger pointing towards heaven. [trans] => 教堂的尖塔在天空的映衬下宛如指向天空的手指。 )

[1] => SimpleXMLElement Object ( [orig] => A balloon floated across the sky. [trans] => 气球飘过天空。 )

[2] => SimpleXMLElement Object ( [orig] => A bolt of lightning lit up the sky. [trans] => (一道)闪电照亮了天空。 )

[3] => SimpleXMLElement Object ( [orig] => A bright moving object appeared in the sky at sunset. [trans] => 日落西山时,天空出现了一个移动的发亮物体。 )

[4] => SimpleXMLElement Object ( [orig] => A bright rainbow arched above. [trans] => 一弯明亮的彩虹悬挂在天空。 )

)

)

“第二部分”将输出

代码如下:
一个移动的发亮物体。 例句:A bright rainbow arched above. 翻译:一弯明亮的彩虹悬挂在天空。

例子,更深入的一个遍历输出生成表格,代码如下:

代码如下:
company."
"; echo $xml->town."
id:"; echo $xml->town['id']."
parent:"; echo $xml->town['parent']."
";

echo "
循环读取:
";
foreach($xml->user as $users){ //有多个user,取得的是数组,循环输出
echo "-------------------
";
echo "姓名:".$users->name."
";
echo "编号:".$users->age."
";
echo "性别:".$users->age['sex']."
";
echo "序号:".$users->height."
";
}

echo "
循环读取:
";
foreach($xml->town as $towns){ //有多个user,取得的是数组,循环输出
echo "-------------------
";
echo "id:".$towns['id']."
";
echo "归属:".$towns['parent']."
";
echo "地区:".$towns."
";
}

希望本文所述对大家的PHP程序设计有所帮助。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐