| Website PHP - Browsing SimpleXML Objects | | Print | |
Website PHP - Browsing SimpleXML Objects
The first rule is “Properties denote element iterators,” which means that you
can loop over all <p> tags in the <body>, like this:
<?php
foreach ($sx2->body->p as $p) {
}
?>
The second states “Numeric indices denote elements,” which means that
we can access the second <p> tag with
<?php
$sx->body->p[1];
?>
The third rule is “Non-numeric indexes denote attributes,” which means
that we can access the background attribute of the body tag with
<?php
echo $sx->body['background'];
?>
The last rule, “String conversion allows access to TEXT data,” means we
can access all text data from the elements. With the following code, we echo
the contents of the second <p> tag (thus combining rules 2 and 4):
<?php
echo $sx->body->p[1];
?>
However, the output doesn’t show Moved to example.org.. Rather, it shows
Moved to .. As you can see, accessing TEXT data from a node will not include
its child nodes. You can use the asXML() method to include child nodes, but this
will also add all the text. Using strip_tags() prevents this. The following
example outputs Moved to example.org:
<?php
echo strip_tags($sx->body->p[1]->asXML()) . "\n";
?>
If you want to iterate over all child elements of the body node, use the
children() method of the SimpleXML element object. The following example
iterates over all children of <body>:
<?php
foreach ($sx->body->children() as $element) {
/* do something with the element */
}
?>
If you want to iterate over all the attributes of an element, the
attributes() method is available to you. Let’s iterate over all the attributes of
the first <a> tag:
<?php
foreach ($sx->body->p[0]->a->attributes() as $attribute) {
echo $attribute . "\n";
}
?>
| Users' Comments (0) |
|
No comment posted






