【问题标题】:how to add a xml node to a symfony Crawler()如何将 xml 节点添加到 symfony Crawler()
【发布时间】:2016-11-29 09:36:17
【问题描述】:

我需要在 saymfony 中管理 xml 文档。

我可以将 xml 放入 Crawler() 实例,修改现有节点,然后将 xml 放入文件中。

但我无法添加新节点。

当我尝试使用 appendChild 方法向父节点添加新节点时,我得到了:

错误的文档错误

当我尝试对爬虫添加方法时,我得到了:

无法向爬虫添加两个不同的来源?

如何向现有爬虫添加简单节点?

感谢您的回复

【问题讨论】:

    标签: xml symfony web-crawler dom-node


    【解决方案1】:

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

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

    得到了

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

    使用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 解决方案几乎相同。

    【讨论】:

    • 感谢您的回复。我忘记了我在哪个项目中遇到了这个问题,我解决了它,但我不记得是如何解决的。我记得代码很干净,我认为它与您的代码几乎相似。抱歉,久违了,我的大脑出现了记忆问题,正在尝试分配 xxxx Ko
    • @VanIllaSkyPEPaPaCinO 不用担心,如果你能找到你的解决方案,那就太好了,我可以把它和我的比较!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-04
    • 1970-01-01
    相关资源
    最近更新 更多