0

i need to add new tag to head section on a HTML page using PHP

actualy i need to add

<link rel="canonical" href="<?php echo 'http://'. $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'] ?>"/>

Hope this can do using PHP DOM

Edited by ruwanaru

2
Contributors
1
Reply
20
Views
1 Year
Discussion Span
Last Post by cereal
0

Yes, it can be done by getting the head element, then by creating an element link, appending the attributes to the created element, and finally appending the new element to the head section.

An example:

<?php

$file = './index.html';

$doc = new DomDocument();
$doc->loadHTMLFile($file);

$head = $doc->getElementsByTagName('head')->item(0);
$link = $doc->createElement('link');

$data = [
    'rel'  => 'canonical',
    'href' => 'http://link.tld/'
    ];

foreach($data as $key => $value)
{
    $attr = $doc->createAttribute($key);
    $attr->value = $value;

    # append the attribute to the element
    $link->appendChild($attr);
}

# append the element to the head section
$head->appendChild($link);

# save the file
$doc->saveHTMLFile($file);

Docs:

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.