I know we can get the heading by loading the string into the
$doc = DOMDocument::loadXML($xml_str);
And then get the H1 tags like so:
$list = $doc->getElementsByTagName("h1");
for ($i = 0; $i < $list->length; $i++) {
print($list->item($i)->nodeValue . "<br/>\n");
}
If i want to change these H1s to H2s I'm a bit lost. I've read about the appendChild()
, but that would make things very messy. Is there a way to recursively demote heading tags in a string that contains html? The method would accept the following parameters:
function demoteHeadings($xml_string, $top_level='H2'){
//if string's highest heading is more than $top_level,
//we demote all headings in this html by 1 level. i.e. if
//h1 is found, all h1s, h2s and so on are demoted one level -
//and we recursively call this function again;
if($top_level_in_xml > $top_level) demoteHeadings($output, $top_level);
}
I hope I make sense. What I'm trying to achieve is auto parsing the headings that my clients enter in their CMS's... They use H1's in the articles, when the title already is a h1. And sometimes, there's also a page title with is a h1, which really messes up the structure on the whole page.
Would it not be simpler to just use str_ireplace()
$content = str_ireplace(array('<h1>','</h1>'),array('<h2>','</h2>'),$input);