如何在扩展DomeElement的自定义类中设置新的HTML标记(在php中使用DOMDocument)?
我需要一个快速的HTML解析器,用php编写。首先,我尝试了一些现有的解析器(比如Ganon或QueryPath),但它们对我的项目来说速度非常慢。最后,我决定使用php内置的DOMDocument,这是最快的。它只有一些简单的方法。所以我必须开始建立我自己的 我正在写一个扩展了DomeElement的类。像“addText”这样的新方法工作得很好,但是当我想更改标记名时,我遇到了一个问题 要更改标记名,必须替换节点。它是另一个节点。在此之后,任何进一步的操作将不再影响节点 更新:现在,我添加了一个如何在扩展DomeElement的自定义类中设置新的HTML标记(在php中使用DOMDocument)?,php,html-parsing,domdocument,Php,Html Parsing,Domdocument,我需要一个快速的HTML解析器,用php编写。首先,我尝试了一些现有的解析器(比如Ganon或QueryPath),但它们对我的项目来说速度非常慢。最后,我决定使用php内置的DOMDocument,这是最快的。它只有一些简单的方法。所以我必须开始建立我自己的 我正在写一个扩展了DomeElement的类。像“addText”这样的新方法工作得很好,但是当我想更改标记名时,我遇到了一个问题 要更改标记名,必须替换节点。它是另一个节点。在此之后,任何进一步的操作将不再影响节点 更新:现在,我添加了
return$newNode在newTag方法中使用code>,我是这样使用的:$node=$node->newTag('h1')代码>但为了保持一致性,我真的只想使用:$node->newTag('h1')代码>
请参阅代码(简化):
理想的解决方案是DOMDocument::renameNode()
,但它在PHP中还不可用
也许这会起作用,称为$node=$node->parentNode->renameChild($node,'h1')
:
是的,这是一个有效的解决方案。请参阅我的更新。但是你认为不是使用$node=$node->newTag('h1')代码>有任何解决方案可以让它工作,只要$node->newTag('h1')代码>?不知何故没有返回$newNode代码>。据我所知,没有使用DOMDocument::renameNode()
。
<?php
class my_element extends DOMElement {
public function __construct() { parent::__construct();}
public function newTag($newTagName) {
$newNode = $this->ownerDocument->createElement($newTagName);
$this->parentNode->replaceChild($newNode, $this);
foreach ($this->attributes as $attribute) {
$newNode->setAttribute($attribute->name, $attribute->value);
}
foreach (iterator_to_array($this->childNodes) as $child) {
$newNode->appendChild($this->removeChild($child));
}
//at this point, $newnode should become $this... How???
}
//append plain text
public function addText ($text = '') {
$textNode = $this->ownerDocument->createTextNode($text);
$this->appendChild($textNode);
}
//... some other methods
}
$html = '<div><p></p></div>';
$dom = new DOMDocument;
$dom->loadHTML($html);
$xPath = new DOMXPath($dom);
$dom->registerNodeClass("DOMElement", "my_element"); //extend DOMElement class
$nodes = $xPath->query('//p'); //select all 'p' nodes
$node = $nodes->item(0); // get the first
//Start to change the selected node
$node->addText('123');
$node->newTag('h1');
$node->addText('345'); //This is not working because the node has changed!
echo $dom->saveHTML();
<?php
class MyDOMNode extends DOMNode {
public function renameChild($node, $name) {
$newNode = $this->ownerDocument->createElement($name);
foreach ($node->attributes as $attribute) {
$newNode->setAttribute($attribute->name, $attribute->value);
}
while ($node->firstChild) {
$newNode->appendChild($node->firstChild);
}
$this->replaceChild($newNode, $node);
return $newNode;
}
}