Accessing Attributes
Where element access makes use of enumerated arrays for accessing multiple elements with the same name on the same hierarchical level, attribute access makes use of associative arrays. The example below uses the same $markupString sample data as in the previous example. <?php // Outputs "thelist" echo $sxe->body->ul['id']; // Outputs "id=thelist" foreach ($sxe->body->ul->attributes() as $name => $value) { echo $name, ' = ', $value, PHP_EOL; } // Another way to output "thelist" $attrs = $sxe->body->ul->attributes(); echo $attrs->id; ?> What the attributes() method actually returns is a SimpleXMLElement instance that provides access to attribute names and values in the same way that SimpleXMLElement normally makes child elements and their values available. As such, the returned instance can be used as the subject of a foreach loop to iterate over the properties that it exposes. <!-- Actual markup --> <ul id="thelist"></ul> <!-- How attributes() exposes it as a SimpleXMLElement instance --> <ul> <id>thelist</id> </ul>
© SimpleXML Extension — Web Scraping >>> Back to TABLE OF CONTENTS <<< | |
Views: 397 | |
Total comments: 0 | |