note 103083 deleted from domelement.getattribute by danbrown
| From: | danbrown@php.net | Date: | Thu, 24 Mar 2011 16:47:11 +0000 |
| Subject: | note 103083 deleted from domelement.getattribute by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-178173@lists.php.net to get a copy of this message | ||
Note Submitter: Anonymous
----
You can also use DOMXPath objects to interleave foreach() in this way is slightly shorter. If you
need a special element or attribute value. The variable $xquery needs xpath expression. This example
filters all group elements as described in xpath query ($xquery), then it filters again the results
by last if condition and stores all attribute names in an object variable of type array
($this->menu).
Benefit: Using class array variable $menu in other class methods. Whenever you need those fields.
XML:
<xml>
<category menu="products">
<groups>
<group menu="vegetables">...</group>
</groups>
</category>
</xml>
<?php
public class example {
public $menu;
function _construct(){}
public function getGroupValueByCategory($xpath_object,$category) {
$xquery =
'//category[normalize-space(@menu)="'.$category.'"]/groups/group';
if($elements = $xpobject->evaluate($xquery)){
$this->menu = array();
}
foreach ($elements as $element) {
if($element->hasAttributes()){
$attributes = $element->attributes;
if(!is_null($attributes)){
foreach ($attributes as $index=>$attr){
if($attr->name == 'menu'){
$this->menu[] = $attr->value;
}
}
}
}
}
}
}
?>
I used this to implement simple menu structure.