先用一段代碼重現一下問題
乍一看,結果很讓人費解:
| 代碼如下 |
|
| $string = << hello world 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等方式擷取)
| 代碼如下 |
|
你好 Array;Array;Array; Haven't seen you for a long time. How are you? 多日不見了,你好嗎? Hello! How are you? 嘿,你好? Hello, Brooks!How are you? 喂,布魯克斯!你好嗎? Hi, Barbara, how are you? 嘿,芭芭拉,你好嗎? How are you? -Quite well, thank you. 你好嗎?-很好,謝謝你。 |
經過simplexml_load_string得到:
| 代碼如下 |
|
| SimpleXMLElement Object ( [@attributes] => Array ( [num] => 219 [id] => 219 [name] => 219 ) [key] => 你好www.111cn.Net [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語言中可以用以下方法取得我們想要的值:
| 代碼如下 |
|
| $data = << 你好 Array;Array;Array; Haven't seen you for a long time. How are you? 多日不見了,你好嗎? Hello! How are you? 嘿,你好? Hello, Brooks!How are you? 喂,布魯克斯!你好嗎? Hi, Barbara, how are you? 嘿,芭芭拉,你好嗎? How are you? -Quite well, thank you. 你好嗎?-很好,謝謝你。 XML; $xmldata = simplexml_load_string($data); header("Content-Type: text/html; charset=UTF-8"); print_r($xmldata); echo " ".trim($xmldata->sent[0]->orig); //Haven't seen you for a long time. How are you? echo " ".trim($xmldata->key); //你好 ?> |
http://www.bkjia.com/PHPjc/733191.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/733191.htmlTechArticle先用一段代碼重現一下問題 乍一看,結果很讓人費解: 代碼如下 ?php $string = EOF data foobarhello/bar/foo foobarworld/bar/foo /data EOF; $data = simplexml_...