微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

php – DOMDocument无法更改parentNode

我无法从null更改DOMDocument parentNode.我尝试过使用appendChild和replaceChild,但没有运气.

我在哪里错了?
    

   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会有点开销.我会使用模板引擎,这意味着将其作为纯文本处理.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐