php - DOMDocument 不能改变 parentNode

标签 php php-5.5

我无法将 DOMDocument parentNode 更改为 null。我试过同时使用 appendChildreplaceChild,但没有成功。

我哪里错了?

   error_reporting(E_ALL);

   function xml_encode($mixed, $DOMDocument=null) {
      if (is_null($DOMDocument)) {
          $DOMDocument =new DOMDocument;
          $DOMDocument->formatOutput = true;
          xml_encode($mixed, $DOMDocument);
          echo $DOMDocument->saveXML();
      } else {
          if (is_array($mixed)) {
              $node = $DOMDocument->createElement('urlset', 'hello');
              $DOMDocument->parentNode->appendChild($node);
          }
      }
  }

  $data = array();

  for ($x = 0; $x <= 10; $x++) {
      $data['urlset'][] = array(
         'loc' => 'http://www.example.com/user',
         'lastmod' => 'YYYY-MM-DD',
         'changefreq' => 'monthly',
         'priority' => 0.5
      );
  }

  header('Content-Type: application/xml');
  echo xml_encode($data);

?>

http://runnable.com/VWhQksAhdIJYEPLj/xml-encode-for-php

最佳答案

由于文档没有节点,您需要将根节点直接附加到文档中,如下所示:

$DOMDocument->appendChild($node);

这是有效的,因为 DOMDocument 扩展了 DOMNode


Working example :

error_reporting(E_ALL);

function xml_encode($mixed, &$DOMDocument=null) {
    if (is_null($DOMDocument)) {
        $DOMDocument =new DOMDocument;
        $DOMDocument->formatOutput = true;
        xml_encode($mixed, $DOMDocument);
        return $DOMDocument->saveXML();
    } else {
        if (is_array($mixed)) {
            $node = $DOMDocument->createElement('urlset', 'hello');
            $DOMDocument->appendChild($node);
        }
    }   
}

$data = array();
for ($x = 0; $x <= 10; $x++) {
    $data['urlset'][] = array(
       'loc' => 'http://www.example.com/user',
       'lastmod' => 'YYYY-MM-DD',
       'changefreq' => 'monthly',
       'priority' => 0.5 
    );  
}

header('Content-Type: application/xml');
echo xml_encode($data);

顺便说一句,如果您只想序列化一个 XML 文件,DOM 有点开销。我会为此使用模板引擎,这意味着将其作为纯文本处理。

关于php - DOMDocument 不能改变 parentNode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30528839/

相关文章:

php - 尝试使用 php 获取子域 URL

php - 安装 pecl/raphf 和 propro 时出错

php - 出现任何错误时停止并返回 Json 响应

mysql - 仅登录第一个用户错误

php - Mysql 行返回数组中的最后一个值,但我期望整行

java - 使用 Java 谈论网络上的一些项目?

php - 预加载在哪里

php - 将变量从 MY_Controller 传递到 View

php - 投票脚本,简化数据库查询的可能性

unicode - 替换 php 字符串中的 unicode 字符的最佳方法是什么?