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

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:


$file = './index.html';

$doc = new DomDocument();

$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

# append the element to the head section

# save the file