使用Php Customized从文件中解析Xml文件

时间:2016-01-22 06:56:37

标签: php xml

我已经停止尝试解析整个xml的代码。某处我犯了错误,我无法从xml文件中获取正确的List。 有40多个部分,每个部分都有不同的部分。 Xml - 4k +行的示例

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的建议?

1 个答案:

答案 0 :(得分: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>';
        }

    }
    ....