小编Kay*_*yla的帖子

PHP DOM XML不会在标记之后打印掉换行符

所以我的问题是当我使用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);
Run Code Online (Sandbox Code Playgroud)

这是我输出的片段:

<topichead>
    <topichead navtitle="blarg blarg"><topicref navtitle="another blarg blarg" href="another blarg blarg"></topicref></topichead>
</topichead>
Run Code Online (Sandbox Code Playgroud)

这只是我的文件的结尾,但是对于我正在替换的标签 - 主题头navtitle ="blarg blarg",附加了topicref,它会在旁边添加,而不是转到下一行.我不能这样读.

如上所示,我尝试过"$ xdoc-> formatOutput = true; $ xdoc-> preserveWhiteSpace = false;"

但这些似乎不起作用 - 它们用标签格式化,但它没有给我正确的换行符.

谢谢=)

php xml dom domdocument

2
推荐指数
1
解决办法
1891
查看次数

通过php domdocument解析器获取文档元素的子元素

好的,这是一个非常常见的xml解析方法,获取子节点,但它只是没有工作它应该如何...

不能从我的根元素中获取一个childNodes数组,但是当我们有子节点时,我可以从任何其他节点获取它,这不是问题.每当我遇到从这个文档元素中获取子节点时,我似乎无法获得的不仅仅是第一个孩子.

我需要从文档元素中获取所有第一级节点.

$xdoc=createDOMDocument($file);
$all_children= $xdoc->documentElement->childNodes;
echo count($all_children);

function createDOMDocument($file){
    $xdoc = new DOMDocument();
    $xdoc->formatOutput = true;
    $xdoc->preserveWhiteSpace  = false;
    $xdoc->load($file);
    return $xdoc;
}
Run Code Online (Sandbox Code Playgroud)

但这只会输出"1",它找不到所有节点,当我试图输出它时,它总是停在第一个节点.这对我来说毫无意义.

它在下面找到的唯一节点是:

<title>some title</title>
Run Code Online (Sandbox Code Playgroud)

如果我删除该节点,它会找到topicmeta等,但绝不会将每个节点都放入一个我需要的数组中.

这是XML:

<?xml version="1.0" encoding="UTF-8"?>
<map title="mytitle" xml:lang="en-us">
<title>some title</title>
<topicmeta>
<prodinfo>
  <prodname>a product</prodname>
      <vrmlist>
        <vrm version="8.5"/>
      </vrmlist>
  <platform/>
</prodinfo>
 </topicmeta>
  <topichead navtitle="cat1" id="topichead4f53aeb751c875.38130575">
<topichead navtitle="another topic"/>
</topichead>
  <topichead navtitle="cat2" id="topichead4f53aeb3596990.18552413"/>
  <topichead navtitle="cat3" id="topichead4f52fd157487f9.21599660"/>
</map>
Run Code Online (Sandbox Code Playgroud)

php xml dom document

2
推荐指数
1
解决办法
2万
查看次数

标签 统计

dom ×2

php ×2

xml ×2

document ×1

domdocument ×1