XML删除关闭/打开标记

时间:2015-03-04 10:18:27

标签: php xml xmlwriter

我想用PHP解析一段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>

我要删除的地方

</amplifications>
<amplifications>

我尝试过使用preg_replace,但似乎我无法弄明白,因为这些标签的缩进方式不同而且有空格。

3 个答案:

答案 0 :(得分:0)

这应该会帮助你。

str_replace("</", "<", $XMLData);

答案 1 :(得分:0)

您可能遇到的第一个问题是默认情况下preg_replace在不同行之间不匹配。

您可以添加修饰符(http://php.net/manual/en/reference.pcre.pattern.modifiers.php)来更改此内容。

  

m(PCRE_MULTILINE)

     

默认情况下,PCRE将主题字符串视为由单个&#34;行&#34;组成。字符(即使它实际上包含几个换行符)。 &#34;行的开头&#34;元字符(^)仅在字符串的开头匹配,而&#34;行的结尾&#34;元字符($)仅匹配字符串的结尾或终止换行符之前(除非设置了D修饰符)。这与Perl相同。当设置此修饰符时,&#34;行的开头&#34; &#34;行尾&#34;构造在主题字符串中的任何换行符之后或之前立即匹配,以及在开始和结束时匹配。这相当于Perl的/ m修饰符。如果没有&#34; \ n&#34;主题字符串中的字符,或模式中没有出现^或$,设置此修饰符无效。

之后,在编写正则表达式时必须小心。这样的事情可能会发生:

<amplifications>
    <amplifications>
    </amplifications>
</amplifications>

并且您不希望将第一个<amplifications>与第一个</amplifications>匹配。如果这种情况不会发生,那么你的正则表达式会更容易编写。

如果您愿意,我可以添加详细信息,但这应该对您有所帮助。

答案 2 :(得分:0)

将具有特定标记名称的所有元素的所有子元素合并到第一个元素中:

示例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>
相关问题