繁体   English   中英

如何使用PHP :: DOMDocument替换元素的内容?

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

我的文档head有很多数据,但我想添加更多数据。 那么如何使用PHP :: DOMDocument替换<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;
}

尝试使用GetElementsByTagName查找<head>标记,然后使用appendChild添加更多内容。 东西。

或者你可以编辑DOMNode->$nodeValue

setAttribute()不适用于DOMText节点。

尝试这个:

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

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

那是因为DOMText类中没有方法setAttribute DOMElement中有一个。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM