2016-01-22 27 views
0

我有休耕碼嘗試解析整個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?

回答

0

問題是您的當前代碼在每次循環迭代時都執行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>'; 
     } 

    } 
    ....