我有两种类型的XML文件,其中包含复古游戏的细节.我正在try 动态编辑文件以搜索和替换游戏标题.
我不确定这个问题是否需要两个不同的解决方案,但我想我会在这里详细说明,希望您能够 bootstrap 我找到一个解决方案.
第一个XML文件具有这种类型的 struct :
<?xml version="1.0" standalone="yes"?>
<LaunchBox>
<Game>
<Status>Imported ROM</Status>
<DatabaseID>22190</DatabaseID>
<Title>ME-Title Match Pro Wrestling</Title>
<UseDosBox>false</UseDosBox>
<Version>(USA)</Version>
</Game>
<Game>
<Status>Imported ROM</Status>
<DatabaseID>30128</DatabaseID>
<Title>Skeet Shoot</Title>
<UseDosBox>false</UseDosBox>
<Version>(USA)</Version>
</Game>
<Game>
<Status>Imported ROM</Status>
<DatabaseID>28694</DatabaseID>
<Title>Star Strike</Title>
<UseDosBox>false</UseDosBox>
<Version>(USA)</Version>
</Game>
</LaunchBox>
第二个文件(扩展名为.dat
,但内部看起来像一个XML)的 struct 如下:
<?xml version="1.0"?>
<!DOCTYPE datafile PUBLIC "-//Logiqx//DTD ROM Management Datafile//EN">
<datafile>
<header>
<name>MatchingDATTest</name>
</header>
<game name="KeepAway (USA)">
<category>Games</category>
</game>
<game name="Super Football Another Game">
<category>Games</category>
</game>
<game name="River Raid II (USA)">
<category>Games</category>
</game>
<game name="London Blitz (USA)">
<category>Games</category>
</game>
</datafile>
我希望能有这样的代码,基本上就是...
查找<Title>Star Strike</Title>
并替换为<Title>Star Wars</Title>
或者,在其他类型的文件的情况下...
查找<game name="KeepAway (USA)">
并替换为<game name="KeepAway 2 (USA)">
我不确定解决这个问题的最好方法是什么?是否fopen
个文件,然后以某种方式逐行通过它,但这些文件可能会变得非常大(多达fopen
,000个游戏),所以我想这可能不实用?在过go 的几天里,经过大量的谷歌搜索和实验,我从其他类似问题的解决方案中拼凑出了这段代码.
这是在try 处理我发布的第一个XML示例.
$reader = new XMLReader();
$reader->open($fileToEdit);
$document = new DOMDocument();
$xpath = new DOMXpath($document);
$found = false;
// look for the document element
do {
$found = $found ? $reader->next() : $reader->read();
} while (
$found &&
$reader->localName !== 'LaunchBox'
);
// go to first child of the document element
if ($found) {
$found = $reader->read();
}
// found a node at depth 1
while ($found && $reader->depth === 1) {
// We need to check if we're dealing with an Element
if ($reader->nodeType == XMLReader::ELEMENT && $reader->name == 'Game')
{
// Let's inspect the node's content as well
while ($reader->read())
{
if ($reader->nodeType == XMLReader::TEXT)
{
$thisValue = $reader->value;
if( $thisValue == $gameTitleToSearchFor ){
$reader->value = $gameTitleToReplaceWith;
break 2;
}
}
}
}
$found = $reader->next();
}
$dom->save($fileToEdit);
$reader->close();
但我收到一个错误,说是Cannot write to read-only property
,所以我挥舞着白旗,因为目前这超出了我的能力范围,所以我想知道是否有人可以帮助我?