У меня много данных в head
моего документа, но я хочу добавить больше данных.Так как я могу заменить содержимое тега <head>
, используя PHP :: DOMDocument ?
У меня есть следующий код:
$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;
}