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:

<?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:

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.