所以我的问题是,当我使用php xml DOM解析器进行保存时,xml文件中的标记没有正确格式化,后面有换行符。
$xdoc = new DOMDocument();
$xdoc->formatOutput = true;
$xdoc->preserveWhiteSpace = false;
$xdoc->load($file);
$new_topic=$xdoc->createElement("topicref", "");
$new_topic->setAttribute("navtitle", $new_node);
$new_topichead=$xdoc->createElement("topichead", "");
$new_topichead->setAttribute("navtitle", $parent_node->getAttribute("navtitle"));
$new_topichead->appendChild($new_topic);
$parent_node->parentNode->replaceChild($new_topichead, $parent_node);
$xdoc->save($file);
以下是我的输出片段:
<topichead>
<topichead navtitle="blarg blarg"><topicref navtitle="another blarg blarg" href="another blarg blarg"></topicref></topichead>
</topichead>
这只是我文件的结尾,但对于我要替换的标签——topichead navtitle="blarg-blarg",加上附加的topicref,它会被固定在它旁边,而不是转到下一行。我不能这样读。
正如您在上面看到的,我已经尝试过"$xdoc->formatOutput=true;$xdoc->preserveWhiteSpace=false;"
但这些似乎不起作用——它们使用制表符进行格式化,但没有给我正确的换行符。
感谢=)
这是一个常见的问题,非常烦人。这有点暴力,但它应该起作用:
// Reload XML to cause format output and/or preserve whitespace to take effect
$xdoc->loadXML($xdoc->saveXML());
$xdoc->save($file);