Home > OS >  How to edit head tag in PHP with DOM with only DOMDocument
How to edit head tag in PHP with DOM with only DOMDocument

Time:03-16

Just trying to edit/modify the head tag in order to add something inside with DOM and PHP.

    $dom = new DOMDocument();
$dom->loadHtml(utf8_decode($html), LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);

for($i=0; $i<count($r);$i  ) 
{
    
    // Prepare the HTML to insert
    Here I want to add $var inside head tag (at the end if possible)
}

return $dom->saveHTML();

Everytime I tried, I have LENGHT=0 as the result of var_dump.

Edit: I don't want to edit an existing tag. I want to add a new one. To be more specific, I need to add OG meta tag for Facebook sharing.

Edit2 as requested :

Before

<head>
    <meta blabla>
    <title></title>
</head>
<body>
    <h1></h1>
</body>

After

<head>
    <meta blabla>
    <title></title>
    <meta new1>
</head>
<body>
    <h1></h1>
</body>

But need to be edit via DOMDocument in PHP...

CodePudding user response:

Add this to the top of your file:

<?php 
     $var = "Hello world.";
?>

Then start the HTML and add it there.

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= $var ?></title>
</head>
<body>
    
</body>
</html>

If you want to do it in PHP, you can try to use:

$titles = $domDocument->getElementsByTagName('title');
foreach($titles as $key => $title){
    $title->setAttribute('attribute', 'value')
}

Source for the edit: https://stackoverflow.com/a/3195048/12077975

CodePudding user response:

Try something along these lines:

$before= 
'<html>
<head>
    <meta name="old"/>
    <title></title>
</head>
<body>
    <h1></h1>
</body>
</html>
';
$HTMLDoc = new DOMDocument();
$HTMLDoc->loadHTML($before, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD );   
$xpath = new DOMXPath($HTMLDoc);

$destination = $xpath->query('//head/title');
$template = $HTMLDoc->createDocumentFragment();
$template->appendXML('<meta name="new"/>');
$destination[0]->parentNode->insertBefore($template, $destination[0]->nextSibling);
echo $HTMLDoc->saveHTML();

Output:

<html>
<head>
    <meta name="old">
    <title></title><meta name="new">
</head>
<body>
    <h1></h1>
</body>
</html
  • Related