1

编辑:与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();
4

2 回答 2

2

明白了,不知道它是如何证明无效的:

$xpath = new \DOMXpath($document);
$nodes = $xpath->query('//img[@id="banner"]');

// Return content if we don't have exactly one image with id="banner"
if(1 !== $nodes->length) return $content;

// DOMNode of the banner
$banner = $nodes->item(0);

// Set the new src attribute and save the content
$banner->setAttribute('src', 'http://mysite.come/img/myimage.png');
$banner->ownerDocument->saveXML($banner);

return $document->saveXML();
于 2012-08-18T02:32:29.977 回答
-2

DOMDocument::getElementById()文档中:

要使此函数起作用,您将需要使用 DOMElement::setIdAttribute 或将属性定义为 ID 类型的 DTD 设置一些 ID 属性。在后一种情况下,您需要在使用此函数之前使用 DOMDocument::validate 或 DOMDocument::$validateOnParse 验证您的文档。

于 2012-08-18T03:08:55.780 回答