note 103083 modified in domelement.getattribute by danbrown

From: Date: Thu, 24 Mar 2011 16:46:42 +0000
Subject: note 103083 modified in domelement.getattribute by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-178172@lists.php.net to get a copy of this message
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. --was-- 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> 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. http://php.net/manual/en/domelement.getattribute.php

« previous php.notes (#178172) next »