我有一段XML有问题,我想用PHP解析它。下面是我的例子:
<tags>
<content>content</content>
<amplifications>
<tag>content 1</tag>
</amplifications>
<amplifications>
<tag>content 2</tag>
<tag>content 3</tag>
<tag>content 4</tag>
<tag>content 5</tag>
</amplifications>
</tags>
我想删除的位置
</amplifications>
<amplifications>
我试过使用preg_replace,但似乎我搞不清楚,因为这些标签的缩进方式不同,而且有空格。
这应该会对您有所帮助。
str_replace("</", "<", $XMLData);
您可能遇到的第一个问题是默认情况下preg_replace
在不同行之间不匹配。
可以添加修改器(http://php.net/manual/en/reference.pcre.pattern.modifiers.php)来改变这一点。
m(PCRE_MULTILINE)
默认情况下,PCRE将主题字符串视为由单个"行"字符组成(即使它实际上包含多个换行符)。"行首"元字符(^)仅在字符串的开头匹配,而"行尾"元字符"$"仅在字符串末尾或终止换行符之前匹配(除非设置了D修饰符)。这与Perl相同。当设置此修饰符时,"行首"answers"行尾"构造分别匹配主题字符串中任何换行符的紧后或紧前,以及最开始和最结束处。这相当于Perl的/m修饰符。如果主题字符串中没有"''n"字符,或者模式中没有出现^或$,则设置此修饰符无效。
之后,在编写regexp时,您必须小心谨慎。类似的事情可能会发生:
<amplifications>
<amplifications>
</amplifications>
</amplifications>
并且您不希望将第一个<amplifications>
与第一个</amplifications>
相匹配。如果这种情况不能发生,那么您的regexp将更容易编写。
如果你愿意,我可以添加细节,但这应该已经对你有所帮助了。
将具有特定标记名的所有元素的所有子元素合并到第一个元素中:
示例XML:
<tags>
<content>content</content>
<amplifications>
<tag>content 1</tag>
</amplifications>
<amplifications>
<tag>content 2</tag>
<tag>content 3</tag>
<tag>content 4</tag>
<tag>content 5</tag>
</amplifications>
</tags>
PHP示例:
$doc = new DOMDocument();
$doc->formatOutput = true;
$doc->preserveWhiteSpace = false;
$doc->loadXML($xml);
$name = 'amplifications';
$elements = $doc->getElementsByTagName($name);
foreach ($elements as $parent) {
if ($elements->item(0) === $parent) {
continue;
}
foreach (iterator_to_array($parent->childNodes) as $child) {
$elements->item(0)->appendChild($child);
}
$parent->parentNode->removeChild($parent);
}
echo $doc->saveXML();
输出:
<?xml version="1.0"?>
<tags>
<content>content</content>
<amplifications>
<tag>content 1</tag>
<tag>content 2</tag>
<tag>content 3</tag>
<tag>content 4</tag>
<tag>content 5</tag>
</amplifications>
</tags>