I’m trying to add a <style> tag within an existing <head> tag. I can’t seem to figure out how to do this for some reason; this is what I’ve come up with so far (by the way, the existing <head> tag is empty):
$dom = new DOMDocument;
$dom->loadHTML($htmlfile_data);
$xpath = new DOMXPath($dom);
$headnode = $xpath->query('//head'); // i assume this is an array?
$stylenode = $dom->createElement('style');
$headnode[0]->appendChild($stylenode);
$htmlfile_data = $dom->saveHTML();
Basically I want the output to be:
before:
<head></head>
after:
<head><style></style></head>
$headnodeis a DOMNodeList object, which can’t be used like an array. Instead, do this:You can use
var_dump($headnode)to see its type.