7

I need to manage xml documents in saymfony.

I've got no problem to get the xml into a Crawler() instance, modify existing node and after it, put the xml into a file.

But i can't add new node.

When i try to add a new node with appendChild method to the parent, i've got:

wrong document error

And when i try the add method to the crawler, i've got:

impossible to add two differents sources to the crawler?

What can i do to add a simple node to an existing crawler?

Thanks for any response

4

1 回答 1

2

我遇到了类似的问题,我试过了:

$crawler=new Crawler($someHtml);
$crawler->add('<element />');

并得到

禁止在同一个爬虫中附加来自多个文档的 DOM 节点。

使用 a DOMDocument,您可以使用它自己的createElement方法来制作节点,然后将它们附加到文档中appendChild或其他。但是由于Crawler似乎没有类似createElement的东西,所以我想出的解决方案是用原生dom文档初始化Crawler,对Crawler做任何你想做的事情,然后将dom文档用作“节点工厂” " 当您需要添加节点时。

我的特殊情况是我需要检查文档是否有head,如果没有,则添加一个(特别是在 body 标记上方添加):

        $doc = new \DOMDocument;
        $doc->loadHtml("<html><body bgcolor='red' /></html>");
        $crawler = new Crawler($doc);
        if ($crawler->filter('head')->count() == 0) {
            //use native dom document to make a head
            $head = $doc->createElement('head');
            //add it to the bottom of the Crawler's node list
            $crawler->add($head);
            //grab the body
            $body = $crawler
                ->filter('body')
                ->first()
                ->getNode(0);
            //use insertBefore (http://php.net/manual/en/domnode.insertbefore.php)
            //to get the head and put it above the body
            $body->parentNode->insertBefore($head, $body);
        }

echo $crawler->html();

产量

<head></head>
<body bgcolor="red"></body>

这似乎有点令人费解,但它确实有效。我正在处理 HTML,但我想 XML 解决方案几乎相同。

于 2018-01-17T21:56:49.090 回答