我有这个类
Class Parser extends DOMDocument {
public function setHTML($file) {
$this->loadHTMLFile($file);
}
public function setAttribute($name, $value) {
return $this->setAttribute($name, $value);
}
public function findById($id) {
return $this->getElementById($id);
}
}
我这样使用它:
$parser = new Parser();
$parser->setHTML('as.html');
$parser->findById("xaxa")->setAttribute('name1', 'value1');
但如果我必须看到更改后的HTML,我会像这个一样调用SAVEHTML
echo $parser->saveHTML();
有没有办法让它自动?类似于调用方法setAttribute以生成
$this->saveHTML()
自动,所以我会有这个
$html =$parser->findById("xaxa")->setAttribute('name1', 'value1');
然后呼叫
echo $html;
感谢
DOM对象不能(直接)用作字符串,当您尝试例如echo时,它将抛出异常
Catchable fatal error: Object of class DOMDocument could not be converted to string in ...
saveHTML方法被明确设计为以HTML字符串的形式返回节点-您可以对此进行回显。请记住,实际上,在调用setAttribute方法后,节点已经被更新(已保存!)-saveHTML只是用于从节点渲染HTML字符串。
如果我理解你的概念,并且你仍然认为你想要按照自己的方式,也许你可以尝试下面的解决方案——但为了记录在案,我没有测试代码。
Class Parser extends DOMDocument
{
public function setHTML($file)
{
$this->loadHTMLFile($file);
}
public function setAttribute($name, $value)
{
return $this->setAttribute($name, $value);
}
public function findById($id)
{
return $this->getElementById($id);
}
public function __toString()
{
return $this->saveHTML();
}
}
// and now this should work
$parser = new Parser();
$parser->setHTML('as.html');
$parser->findById("xaxa")->setAttribute('name1', 'value1');
echo $parser;