php中simplexml_load_string使用实例
在php中simplexml_load_string() 函数把 XML 字符串载入对象中,下面我来给大家介绍几个简单实例的同时也介绍在使用simplexml_load_string的一些需要注意的事项.
先用一段代码重现一下问题,乍一看,结果很让人费解,代码如下:
<?php $string = <<<EOF <data> <foo><bar>hello</bar></foo> <foo><bar>world</bar></foo> </data> EOF; $data = simplexml_load_string($string); print_r($data); print_r($data->foo); ?>
登入後複製
SimpleXMLElement Object ( [foo] => Array ( [0] => SimpleXMLElement Object ( [bar] => hello ) [1] => SimpleXMLElement Object ( [bar] => world ) ) ) SimpleXMLElement Object ( [bar] => hello )
登入後複製
明明print_r显示foo是一个有两个bar元素的数组,但是最后却仅仅显示了一个bar元素,原因其实很简单,在如上所示simplexml_load_string的结果里,foo并不是数组,而是一个迭代对象.
可以这样确认,代码如下:
foreach ($data->foo as $v) print_r($v); foreach ($data->children() as $v) print_r($v);
登入後複製
看来,print_r或者var_dump之类的表象并不完全可信,假如我们获取的XML数据如下,可以使用curl、fsockopen等方式获取,代码如下:
<?xml version="1.0" encoding="UTF-8" <dict num="219" id="219" name="219"> <key>你好</key> <pos></pos> <acceptation>Array;Array;Array;</acceptation> <sent> <orig>Haven't seen you for a long time. How are you?</orig> <trans>多日不见了,你好吗?</trans> </sent> <sent> <orig>Hello! How are you?</orig> <trans>嘿,你好?</trans> </sent> <sent> <orig>Hello, Brooks!How are you?</orig> <trans>喂,布鲁克斯!你好吗?</trans> </sent> <sent> <orig>Hi, Barbara, how are you?</orig> <trans>嘿,芭芭拉,你好吗?</trans> </sent> <sent> <orig>How are you? -Quite well, thank you.</orig> <trans>你好吗?-很好,谢谢你。</trans> </sent> </dict>
登入後複製
经过simplexml_load_string得到如下代码:
SimpleXMLElement Object ( [@attributes] => Array ( [num] => 219 [id] => 219 [name] => 219 ) [key] => 你好www.phprm.com [pos] => SimpleXMLElement Object ( ) [acceptation] => Array;Array;Array; [sent] => Array ( [0] => SimpleXMLElement Object ( [orig] => Haven't seen you for a long time. How are you? [trans] => 多日不见了,你好吗? ) [1] => SimpleXMLElement Object ( [orig] => Hello! How are you? [trans] => 嘿,你好? ) [2] => SimpleXMLElement Object ( [orig] => Hello, Brooks!How are you? [trans] => 喂,布鲁克斯!你好吗? ) [3] => SimpleXMLElement Object ( [orig] => Hi, Barbara, how are you? [trans] => 嘿,芭芭拉,你好吗? ) [4] => SimpleXMLElement Object ( [orig] => How are you? -Quite well, thank you. [trans] => 你好吗?-很好,谢谢你。 ) ) )
登入後複製
我们在PHP语言中可以用以下方法取得我们想要的值,代码如下:
".trim($xmldata->sent[0]->orig); //Haven't seen you for a long time. How are you? echo "
".trim($xmldata->key); //你好
登入後複製
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章
<🎜>:種植花園 - 完整的突變指南
3 週前
By DDD
<🎜>:泡泡膠模擬器無窮大 - 如何獲取和使用皇家鑰匙
3 週前
By 尊渡假赌尊渡假赌尊渡假赌
如何修復KB5055612無法在Windows 10中安裝?
3 週前
By DDD
北端:融合系統,解釋
3 週前
By 尊渡假赌尊渡假赌尊渡假赌
藍王子:如何到達地下室
4 週前
By DDD

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)