提取节点值&使用php从大型嵌套xml文档中获取属性值(父节点和子节点)

时间:2017-10-03 04:14:30

标签: php xml export-to-csv xmlreader

我正在尝试提取提取节点值&来自大型嵌套xml文档的属性值(父节点和子节点)。输出应该是表格的形式。使用我的代码,我可以提取名为&#34的文本值; N2:NameElement N2:ElementType =" FullName""和属性值命名为" PartyID"父节点(N8:Entity),但不是名为&#34的属性值; N5:IndustryCode"子节点" N5:OrganisationInfo" see my output table - the column for attribute value of N5:IndustryCode is blank。这是我的虚拟文件:xml file

目标子节点属性命名为" N5:IndustryCode"在名为" N5:OrganisationInfo"的标签下。

这是我的代码:

 <?php
 error_reporting ( E_ALL );
 ini_set ( 'display_errors', 1 );
 ini_set("max_execution_time", 0);

 $reader = new XMLReader();

 $reader->open("xmlfile.xml");
 $fo = fopen("companiesNameNzbnBizClassification_WholeData1.csv", "w" );
 fputs($fo, "name, ID,businessClassification".PHP_EOL);
 while ( $reader->read())    {

if ( $reader->name == 'N8:Entity'  &&
        $reader->nodeType === XMLReader::ELEMENT &&
        $reader->localName == 'Entity' && $reader->localName == 
 'IndustryCode')    {
            $name = null;
            $businessClassification = null;
            $ID = null;
            $newNode = $reader->expand();

            $nameNode = $newNode->getElementsByTagName('OrganisationName');
            if ( $nameNode->length > 0 ){
                $name = $nameNode[0]->getElementsByTagName('NameElement')-
 >item(0)->nodeValue;
            }

            $ID = (string)$reader->getAttribute('PartyID'); 
            $businessClassification = (string)$reader-
 >getAttribute('IndustryCode');             

            $newName = str_ireplace(","," ",$name);
            fputs($fo,  
  $newName.",".$ID.",".$businessClassification.PHP_EOL);

        }       
 }
 fclose($fo);

我很乐意为你提供帮助。感谢。

0 个答案:

没有答案