James Nine
James Nine

Reputation: 2618

in PHP, how to add a tag within an existing one?

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>

Upvotes: 0

Views: 79

Answers (1)

JW.
JW.

Reputation: 51638

$headnode is a DOMNodeList object, which can't be used like an array. Instead, do this:

$headnode->item(0)->appendChild($node);

You can use var_dump($headnode) to see its type.

Upvotes: 2

Related Questions