如何在此xml中计算项目/记录的数量-通过"item"表示"productItem"元素,即示例xml中有5个项目.解析xml时,我没有指定标签名称'productItem',所以我无法计算'productItem'的出现次数.这是我的代码: <?php$ doc =新的DOMDocument();$ doc-> load("test.xml");$ xpath =新的DOMXpath($ doc);$ nodes = $ xpath-> query('//* |//@ *');$ nodeNames = array();foreach($ nodes作为$ node){$ nodeNames = $ node-> nodeName;$ name = $ node-> nodeName;$ value = $ node-> nodeValue;回声''.$ name.':'.$ value.'< br>';}?> 如何统计项目的数量并逐个显示它们,就像这样理想: http://goo.gl/O1FI8 吗?解决方案为什么不使用DOMDocument :: getElementsByTagName? //获取产品数量echo $ doc-> getElementsByTagName('productitem')->长度;//遍历productitem的集合foreach($ doc-> getElementsByTagName('productitem')作为$ element){//$ element是一个DOMElement$ nodeNames = $ element-> nodeName;$ name = $ element-> nodeName;$ value = $ element-> nodeValue;回声''.$ name.':'.$ value.'< br>';} 当您要遍历文档时,使用XPath只是贪婪.而且,即使您只想要一个或两个,您也将实例化文档的每个节点.您可以使用hasChildNodes方法和childNodes属性遍历文档 函数searchInNode(DOMNode $ node){if(isGoodNode($ node)){//如果根据您的数据库您的节点是好的mapTheNode($ node);}if($ node-> hasChildNodes()){foreach($ node-> childNodes作为$ nodes){searchInNode($ nodes);}}}searchInNode($ domdocument); I have to parse xml files that look like this : http://goo.gl/QQirqHow can I count number of items/records in this xml- by 'item' I mean a 'productItem' element, ie there are 5 items in the example xml. I don't specify the tag name 'productItem' when parsing the xml, so I can't count occurrences of 'productItem'. Here is the code I have: <?php$doc = new DOMDocument();$doc->load("test.xml");$xpath = new DOMXpath( $doc );$nodes = $xpath->query( '//*| //@*' );$nodeNames = array();foreach( $nodes as $node ){ $nodeNames = $node->nodeName; $name=$node->nodeName; $value=$node->nodeValue; echo ''.$name.':'.$value.'<br>'; }?>How can I count number of items and display them one by one, like this ideally : http://goo.gl/O1FI8 ? 解决方案 Why don't you use DOMDocument::getElementsByTagName?//get the number of product itemsecho $doc->getElementsByTagName('productitem')->length; //traverse the collection of productitemforeach($doc->getElementsByTagName('productitem') as $element){ //$element is a DOMElement $nodeNames = $element->nodeName; $name=$element->nodeName; $value=$element->nodeValue; echo ''.$name.':'.$value.'<br>';}As you want to traverse your document, use XPath is just greedy. Moreover you will instantiate each node of the document even if you only want one or two.You can use hasChildNodes methode and childNodes attribute to traverse your documentfunction searchInNode(DOMNode $node){ if(isGoodNode($node)){//if your node is good according to your database mapTheNode($node); } if($node->hasChildNodes()){ foreach($node->childNodes as $nodes){ searchInNode($nodes); } }}searchInNode($domdocument); 这篇关于用php计算xml中的项目数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
09-11 12:20