编辑:与PHP HTML DomDocument getElementById 问题相关
无法getElementById()
上班。文档有效,根据使用 W3C 验证器。另外,即使有一点无效的 HTML,我的代码也应该可以工作。
这个简单的代码查找一个图像id="banner"
并将其src
属性替换为另一个图像。适用于我的开发机器(Windows),不适用于服务器(Ubuntu)。
知道如何在没有 的情况下执行此操作getElementById()
吗?
libxml_use_internal_errors(true);
// Create the DOMDocument and get the HTML content
$document = new \DOMDocument();
// Load HTML string and if it fails just return the content itself
if(false === $document->loadHTML($content)) return $content;
// Get DOMElement of the image with id="banner"
$img = $document->getElementById('banner');
// Return the content if it can't find the image
if(null === $img) return $content;
// Get image parent and remove the banner from DOM
$parent = $img->parentNode;
$parent->removeChild($img);
// Set the new src attribute
$img->setAttribute('src', 'http://mysite.come/img/myimage.png');
// Append the modified node to banner parent
$parent->appendChild($img);
return $document->saveHTML();