PHP DOM getElementbyID并追加它?

时间:2016-07-09 13:30:46

标签: php domdocument

对于我的网站,如果设置了sessionname,我想删除并添加内容。 对于删除我使用此代码:

$this->removeContent = $xpath->query('//html:a[@class="btn btnLogin"]')->item(0);
$this->removeContent->parentNode->removeChild($this->removeContent);

效果很好。 现在是我的问题,我可以添加内容吗?

我试图通过ID名称获取它并附加它,但我不知道如何。

$btnLogout = $dom->getElementById('btnLogout');
$this->add_content = $xpath->query('//html:div[@class="head"]')->item(0);
$this->add_content->appendChild($dom->importNode($btnLogout, true));

错误:可捕获的致命错误:传递给DOMDocument :: importNode()的参数1必须是DOMNode的一个实例,给定null,在第46行的/var/www/ProjectX/src/Controllers/FrontPageController.php中调用并定义在第43行的/var/www/ProjectX/src/Renderers/FrontPageRenderer.php

此文件的整个PHP代码:

<?php
/**
 * Created by PhpStorm.
 * User: Lukas
 * Date: 20.05.2016
 * Time: 23:41
 */

namespace ProjectX\Renderers {

    use DOMDocument;
    use DOMXPath;

    class FrontPageRenderer
    {
        /**
         * @var
         *
         */
        private $add_content;

        private $removeContent;

        //Rendert die Frontpage mit hilfe von DOMDocument
        public function renderFrontpage($template, $content)
        {
            $dom = new DOMDocument();
            $xpath = new DOMXPath($dom);

            $xpath->registerNamespace('html', "http://www.w3.org/1999/xhtml");

            $dom->appendChild($dom->importNode($template->documentElement, true));
            //Added den Content der Seite in der Class main. 
            $this->add_content = $xpath->query('//html:div[@class="main"]')->item(0);
            $this->add_content->appendChild($dom->importNode($content->documentElement, true));
            //Remove Content
            $this->removeContent = $xpath->query('//html:a[@class="btn btnLogout"]')->item(0);
            $this->removeContent->parentNode->removeChild($this->removeContent);

            if(isset($_SESSION['name'])) {
                $btnLogout = $dom->getElementById('btnLogout');
                $this->add_content = $xpath->query('//html:div[@class="head"]')->item(0);
                $this->add_content->appendChild($dom->importNode($btnLogout, true));

                $this->removeContent = $xpath->query('//html:a[@class="btn btnLogin"]')->item(0);
                $this->removeContent->parentNode->removeChild($this->removeContent);
                $this->removeContent = $xpath->query('//html:a[@class="btn btnRegister"]')->item(0);
                $this->removeContent->parentNode->removeChild($this->removeContent);
            }
            return $dom->saveXML();
        }

    }
}

我如何添加内容?

0 个答案:

没有答案