如何使用 PHP::D OMDocument 替换元素的内容


How can I replace the contents of an element using PHP::DOMDocument?

我的文档head中有很多数据,但我想添加更多数据。那么如何使用 PHP::D OMDocument 替换 <head> 标签的内容呢?

我有以下代码:

$dom = new DOMDocument('1.0', 'UTF-8');
@$dom->loadHTML($page);
$head = $dom->getElementsByTagName('head');
$keywords = new DOMElement('meta');
keywords->setAttribute('name', 'keywords');
$keywords->setAttribute('content', $page_def['keywords']);
$head->appendChild($keywords);
$description = new DOMElement('meta');
$description->setAttribute('name', 'description');
$description->setAttribute('content', $page_def['description']);
$head->appendChild($description);
$page = $dom->saveHTML();
page::dump($page);return;

但是我收到一个错误:调用未定义的方法DOMText::setAttribute()

编辑:我最终发现使用PHP:DOMDocument非常困难。在这种情况下,我使用了以下代码:

// Add the small meta data set to the header
$page = utility::replaceStringBetween('<head>', '</head>', $header . $headers, $page);
if (utility::getReplacementCount() == 0)
{
    $error = "During page write: The head tags could not be modified within your page";
    if (settings::getConfig('context') == 'production')
    {
        if (settings::getConfig('log_enabled') == 'true')
        {
            dblog::insert(user::getId(), $error, 'error');
        }
    }
    // So the live pages will display correctly, unset the merge mode since the process which unsets it will fail to execute
    if (isset($_SESSION['merge_mode'])) unset($_SESSION['merge_mode']);
    print $error;
    return;
}
/**
* Replace the value between two other values in a string
* 
* @param string start delimeter
* @param string end delimeter
* @param string replacement
* @param string original source
* @param int limit replacement count
* @return string
*/
public static function replaceStringBetween($start, $end, $new, $source, $limit = 1)
{
    $result = preg_replace('#('.preg_quote($start) . ')(.*)('.preg_quote($end) 
        . ')#is', '$1' . $new . '$3', $source, $limit, $count);
    if ($count > 0)
    {
        self::$replacement_count++;
        return $result;
    }
    $result = preg_replace ("#{$start}(.*){$end}#is", $new, $source, $limit, $count);
    if ($count > 0)
    {
        self::$replacement_count++;
        return $result;
    }
    return $source;
}
setAttribute()

DOMText节点上不起作用。

试试这个:

$keywords = $dom->createElement('meta');

尝试使用 GetElementsByTagName 查找<head>标签,然后追加 Child 添加更多 . . .东西。

或者,您可以编辑DOMNode->$nodeValue

但是我收到一个错误:调用未定义 方法 DOMText::setAttribute()

这是因为 DOMText 类中没有方法setAttribute。在穹顶中有一个。