使用 Php 自定义从文件中解析 XML 文件


Parse Xml File from file with Php Customized

我有休耕代码来尝试解析整个XML。我犯了错误,无法从xml文件中获取正确的列表。有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 的任何建议?

问题是您当前的代码在每次循环迭代中都执行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>';
        }
    }
    ....