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>

A Debugging Bug

Bug #44973, which affects the SimpleXML extension, is reported to be present in PHP 5.2.6 and may be present in other versions as well. The bug is exposed when an attempt is made to output a node accessed via a SimpleXMLElement instance using echo, print_r(), var_dump(), and other similar functions. If the node has both attributes and a text value, the attributes will not be shown in the output of these functions. This does not mean that attribute values are not accessible in this situation; they simply can't be output in this fashion unless referenced directly. More information on this is available at http://bugs.php.net/bug.php?id=44973.


© SimpleXML Extension — Web Scraping

>>> Back to TABLE OF CONTENTS <<<
Category: Article | Added by: Marsipan (03.09.2014)
Views: 328 | Rating: 0.0/0
Total comments: 0
avatar