From: Marcus Boerger Date: Sat, 29 Oct 2005 20:38:30 +0000 (+0000) Subject: - Add new example X-Git-Tag: RELEASE_2_0_1~117 X-Git-Url: https://granicus.if.org/sourcecode?a=commitdiff_plain;h=bf0f8445216b0324405a83541eb2705fa6c523ca;p=php - Add new example --- diff --git a/ext/spl/examples/xml_xpath_tree.php b/ext/spl/examples/xml_xpath_tree.php new file mode 100755 index 0000000000..781ac12c2b --- /dev/null +++ b/ext/spl/examples/xml_xpath_tree.php @@ -0,0 +1,122 @@ + \ [\] + * + * Simply specify the xml file to tree with parameter \. + * + * The second parameter is a xpath expression to be evaluated. + * + * The third parameter allows to output a maximum of \ characters of + * the element or attribute value. + */ + +if ($argc < 3) { + echo << + +Displays a graphical tree for the elements in []. + + The file for which to generate the tree graph. + An XPath expression to evaluate. + Max length to display for attribute and element content (default: 0). + + +EOF; + exit(1); +} + +if (!class_exists("RecursiveTreeIterator", false)) require_once("recursivetreeiterator.inc"); + +class SimpleXmlStructure extends AppendIterator implements RecursiveIterator +{ + function __construct($xml) + { + parent::__construct(); + if (!is_null($xml)) + { + $xml = is_object($xml) ? $xml : $xml = simplexml_load_file($xml, 'SimpleXmlIterator'); + $this->append($xml); + $attr = $xml->attributes(); + if ($attr) + { + $this->append($attr); + } + } + } + + function key() + { + return ($this->getIteratorIndex() ? '@' : '') . parent::key(); + } + + function hasChildren() + { + return $this->getInnerIterator()->hasChildren() + || !$this->getIteratorIndex(); + } + + function getChildren() + { + $inner = $this->getInnerIterator(); + return $this->getIteratorIndex() + ? $inner->getChildren() + : new SimpleXmlStructure($inner->getChildren()); + } + + function current() + { + global $len; + + if ($len) + { + $val = substr(parent::current(), 0, $len); + $nws = preg_replace("/([\r\n]|\s\s+)/e", " ", $val); + return ($this->getIteratorIndex() ? '= ' : ': ') . $nws; + } + else + { + return ''; + } + } +} + +class SimpleXMLXPathResult extends RecursiveArrayIterator +{ + function __construct($file, $xpath) + { + $xml = @simplexml_load_file($file, 'SimpleXmlIterator'); + parent::__construct($xml ? $xml->xpath($xpath) : NULL); + } + + function current() + { + return ''; + } + + function hasChildren() + { + return true; + } + + function getChildren() + { + return new SimpleXmlStructure(parent::current()); + } +} + +$len = isset($argv[3]) ? $argv[3] : 0; +$xml = new SimpleXMLXPathResult($argv[1], $argv[2]); +$it = new RecursiveTreeIterator($xml, RecursiveTreeIterator::BYPASS_CURRENT); +foreach($it as $c=>$v) +{ + echo "$c$v\n"; +} + +?> \ No newline at end of file