我大部分的 XML 解析生命都花在从大量的 XML(亚马逊 MWS)中提取有用信息的块。因此,我的回答假设您只需要特定信息并且您知道它的位置。
我发现使用 XMLReader 最简单的方法是知道我想从哪些标签中获取信息并使用它们。如果您知道 XML 的结构并且它有很多独特的标签,我发现使用第一种情况很容易。案例 2 和案例 3 只是为了向您展示如何处理更复杂的标签。这是非常快的;我在什么是 PHP 中最快的 XML 解析器?
像这样进行基于标签的解析时要记住的最重要的事情是使用if ($myXML->nodeType == XMLReader::ELEMENT) {...
- 检查以确保我们只处理打开节点而不是空白或关闭节点或其他任何东西。
function parseMyXML ($xml) { //pass in an XML string
$myXML = new XMLReader();
$myXML->xml($xml);
while ($myXML->read()) { //start reading.
if ($myXML->nodeType == XMLReader::ELEMENT) { //only opening tags.
$tag = $myXML->name; //make $tag contain the name of the tag
switch ($tag) {
case 'Tag1': //this tag contains no child elements, only the content we need. And it's unique.
$variable = $myXML->readInnerXML(); //now variable contains the contents of tag1
break;
case 'Tag2': //this tag contains child elements, of which we only want one.
while($myXML->read()) { //so we tell it to keep reading
if ($myXML->nodeType == XMLReader::ELEMENT && $myXML->name === 'Amount') { // and when it finds the amount tag...
$variable2 = $myXML->readInnerXML(); //...put it in $variable2.
break;
}
}
break;
case 'Tag3': //tag3 also has children, which are not unique, but we need two of the children this time.
while($myXML->read()) {
if ($myXML->nodeType == XMLReader::ELEMENT && $myXML->name === 'Amount') {
$variable3 = $myXML->readInnerXML();
break;
} else if ($myXML->nodeType == XMLReader::ELEMENT && $myXML->name === 'Currency') {
$variable4 = $myXML->readInnerXML();
break;
}
}
break;
}
}
}
$myXML->close();
}