从文件解析XML文件与PHP自定义

问题描述:

我有休耕码尝试解析整个XML。某处我犯了错误,我无法从xml文件中获取正确的列表。 有40多个部分,每个部分都有不同。的XML 实例 - 4K +线从文件解析XML文件与PHP自定义

XML

<ItemList> 
    <Section Index="0" Name="Swords"> 
<Item Index="0" Slot="0" SkillIndex="0" Name="Kris" /> 
<Item Index="1" Slot="4" SkillIndex="0" Name="Blade" /> 
++++ 
++++ 
+++ 
++ 
+ 

    </Section> 
    <Section Index="1" Name="Axes"> 
    <Item Index="0" Slot="0" SkillIndex="0" Name="Small Axe" /> 
    <Item Index="1" Slot="1" SkillIndex="0" Name="Hand Axe" /> 
    ++++ 
    ++++ 
    ++ 
    ++ 
    + 
    </Section> 
    sections goes more... 
    </ItemList> 

** PHP代码修正XML解析**人无我有问题txt文件编写。

$grabUrl = "Item.xml"; 

$xml = new XMLReader; 
$xml->open($grabUrl); 
while ($xml->read()) { 
    if ($xml->nodeType === XMLReader::ELEMENT && $xml->name == 'Section') 
    //$node = $xml->expand(); 
     echo $xml->getAttribute('Index').' <br>'; 
      if ($xml->nodeType === XMLReader::ELEMENT && $xml->name == 'Item') 
       echo 'Type:'.$xml->getAttribute('Index').' Section Name :'.$xml->getAttribute('Name').' <br>'; 


$data = ''; 
$LogFileLocation = __PATH_CACHE__."Tracker/".date('F_j_Y').".txt"; 
$db    = fopen($LogFileLocation,'at');  
$data   .= ''.$xml->getAttribute('Index').'\t'.$xml->getAttribute('Name').'\n'; 
$data   .=''.$xml->getAttribute('Index').'\t'.$xml->getAttribute('Name').'\n'; 
fwrite($db,''.$xml->getAttribute('Index').'\t'.$xml->getAttribute('Name').'\n';); 
fclose($db); 

} 

输出

Index: Name : 
Index: Name : 
Index: Name : 
Index:0 Name :Swords 
Index: Name : 
Index:0 Name :Kris 
Index: Name : 
Index:1 Name :Short Sword 
Index: Name : 

我的问题是怎样才能得到输出如下。提前感谢您的帮助。

Section Index : 0 Name: Swords 
Item Index:0 Name :Kris 
Item Index:1 Name :Short Sword 
end 
Section Index : 1 Name: Axes 
Item Index:0 Name :Small Axe 
Item Index:1 Name :Hand Axe 
++ 
end 

go on... 

编辑

代码修正,现在我能得到我想要的东西。问题是我不能解析它的txt文件。任何建议将xml结果解析为txt?

问题是您的当前代码在每次循环迭代时都执行echo构造。您应该在if运营商的条件下执行输出,如下所示:

... 
    $xml->open($XmlFile); 
    while ($xml->read()) { 
     if ($xml->nodeType === XMLReader::ELEMENT && $xml->name == 'Item'){ 
      $node = $xml->expand(); 
      echo 'Index:'.$xml->getAttribute('Index').' Name :'.$xml->getAttribute('Name').'<br>'; 
     } 

    } 
    ....