simpleXML中,將xml檔案轉成了一個對象,根節點就是這個對象,訪問子節點就是對象的成員屬性。有下面這個xml文檔:
如何成功?張三39.8成功人士應該有的特質李四42.8
$xml_obj=simplexml_load_file("books.xml"); $books=$xml_obj->book;$book=$books[0]; //這是第一本書,他是一個對象,他下面的子節點可以通過訪問他的成員方法擷取,但是他的屬性,,,,,,$lang=$book["lang"];//擷取他的屬性,lang。以數組的方式訪問,但是他不是一個對象嗎?
我不明白的地方是這樣的,訪問節點屬性的時候是以數組的方式去訪問的,但是$book是一個對象啊!怎麼變成數組了?
回複討論(解決方案)
http://www.php.net/manual/zh/class.arrayaccess.php
[book] => Array
(
[0] => SimpleXMLElement Object
(
[@attributes] => Array
(
[lang] => 中文
)
[name] => 如何成功?
[author] => 張三
[price] => 39.8
)
摘錄手冊一段,留意紅色部分:
-------------------------------------------------------
The SimpleXMLElement class
(No version information available, might only be in SVN)
簡介
Represents an element in an XML document.
類摘要
SimpleXMLElement implements Traversable {
……
-----------------------------------------------------------------
Traversable 是SPL的一個類(目前手冊並無具體介紹,但去 php.net 能發掘到)
再摘錄一小段給你
-----------------------------------------------------------------------------
Traversable Interface Reference
[Zend engine classes]
Interface to detect a class is traversable using foreach. More...
Detailed Description
Interface to detect a class is traversable using foreach. //這就意味著是可迭代對象
Since:
PHP 5.0
Abstract base interface that cannot be implemented alone. Instead it must be implemented by either IteratorAggregate or Iterator.
Note:
Internal classes that implement this interface can be used in a foreach construct and do not need to implement IteratorAggregate or Iterator.
This is an engine internal interface which cannot be implemented in PHP scripts. Either IteratorAggregate or Iterator must be used instead.
Definition at line 509 of file spl.php.
--------------------------------------------------------------------------------
The documentation for this interface was generated from the following file:
spl.php
[book] => Array
(
[0] => SimpleXMLElement Object
(
[@attributes] => Array
(
[lang] => 中文
)
[name] => 如何成功?
[author] => 張三
[price] => 39.8
)
[@attributes] => Array
這裡的@是什麼意思啊?我對正宗的數組var_dump沒有出現這個@符號。
SimpleXMLElement 對象的屬性數組
一般用遍曆 attributes 方法返回的數組進行操作
你那樣寫也是可以的