Use DomDocument to replace all header tags with the h4 tags

自古美人都是妖i 提交于 2019-12-30 12:04:42

问题


I've used DomDocument to to GetElementById. It has selected a div. I need to replace all the header tags within that div with the h4 tag.


回答1:


You have not made clear in your question what the concrete problem is you run into. I would assume that there are two parts that could cause you some questions marks.

The first one would be how to get the hand on all the elements that you want to rename and the second one is actually how to rename an element.

Get Heading Elements of a DOMDocument

So first things first: To select all the header elements you need to select all tags that are Heading elements (h1 to h6). Combined with the condition that they also need to be children of the div tag with a specific id attribute this seems like a rather complicate thing to do. However with an xpath query, it is still merely straight forward.

Exemplary for my code examples I have choosen the id `"content" and the following xpath expression queries all heading elements:

(
    //div[@id="content"]//h1
    |//div[@id="content"]//h2
    |//div[@id="content"]//h3
    |//div[@id="content"]//h4
    |//div[@id="content"]//h5
    |//div[@id="content"]//h6
)

If I run this on this website here (before I answered it), it creates the following listing of tags:

Found 8 elements:
 #00: <h1>
 #01: <h2>
 #02: <h2>
 #03: <h3>
 #04: <h3>
 #05: <h3>
 #06: <h2>
 #07: <h4>

As this demonstrates well, with an xpath query even a list of different elements and with specific conditions like being a child of the div with the id can be created. This code at a glance:

$url = 'http://stackoverflow.com/questions/16307103/use-domdocument-to-replace-all-header-tags-with-the-h4-tags';

$dom = new DOMDocument();
$internalErrorsState = libxml_use_internal_errors(true);
$dom->loadHTMLFile($url);
libxml_use_internal_errors($internalErrorsState);
$xpath = new DOMXPath($dom);

$expression = '
(
    //div[@id="content"]//h1
    |//div[@id="content"]//h2
    |//div[@id="content"]//h3
    |//div[@id="content"]//h4
    |//div[@id="content"]//h5
    |//div[@id="content"]//h6
)';

$elements = $xpath->query($expression);
echo "Found ", $elements->length, " elements:\n";
foreach ($elements as $index => $element) {
    printf(" #%02d: <%s>\n", $index, $element->tagName);
}

Renaming a DOMElement

So what about the second problem, about renaming elements?

DOMDocumet out of the box does not support this. There is a method stub (DOMDocument::renameNode(); undocumented in the current PHP manual) but if you call it you get a warning that it is not implemented:

Warning: DOMDocument::renameNode(): Not yet implemented

Instead one needs to roll her own version. And this is how it works: As you can not rename an element with DOMDocument, all you can do is to create a new element with the renamed name and copy the node to rename all its attributes and children into it and then replace it with the renamed shallow copy. This is done by the following method:

/**
 * Renames a node in a DOM Document.
 *
 * @param DOMElement $node
 * @param string     $name
 *
 * @return DOMNode
 */
function dom_rename_element(DOMElement $node, $name) {
    $renamed = $node->ownerDocument->createElement($name);

    foreach ($node->attributes as $attribute) {
        $renamed->setAttribute($attribute->nodeName, $attribute->nodeValue);
    }

    while ($node->firstChild) {
        $renamed->appendChild($node->firstChild);
    }

    return $node->parentNode->replaceChild($renamed, $node);
}

Bringing this together with the foreach loop from above, next to outputting the tag-names, they can also be renamed:

$elements = $xpath->query($expression);
echo "Found ", $elements->length, " elements:\n";
foreach ($elements as $index => $element) {
    printf(" #%02d: <%s>\n", $index, $element->tagName);
    dom_rename_element($element, 'h4');
    ###################################
}

And then afterwards, querying the xpath expression again, will result in h4 tags only:

$elements = $xpath->query($expression);
echo "Found ", $elements->length, " elements:\n";
foreach ($elements as $index => $element) {
    printf(" #%02d: <%s>\n", $index, $element->tagName);
}

Output:

Found 8 elements:
 #00: <h1>
 #01: <h2>
 #02: <h2>
 #03: <h3>
 #04: <h3>
 #05: <h3>
 #06: <h2>
 #07: <h4>

Full Code-Example

Here the full code-example and its output at a glance:

<?php
/**
 * Use DomDocument to replace all header tags with the h4 tags
 * @link http://stackoverflow.com/q/16307103/367456
 */
$url = 'http://stackoverflow.com/questions/16307103/use-domdocument-to-replace-all-header-tags-with-the-h4-tags';

$dom = new DOMDocument();
$internalErrorsState = libxml_use_internal_errors(true);
$dom->loadHTMLFile($url);
libxml_use_internal_errors($internalErrorsState);
$xpath = new DOMXPath($dom);

$expression = '
(
    //div[@id="content"]//h1
    |//div[@id="content"]//h2
    |//div[@id="content"]//h3
    |//div[@id="content"]//h4
    |//div[@id="content"]//h5
    |//div[@id="content"]//h6
)';

$elements = $xpath->query($expression);
echo "Found ", $elements->length, " elements:\n";
foreach ($elements as $index => $element) {
    printf(" #%02d: <%s>\n", $index, $element->tagName);
    dom_rename_element($element, 'h4');
}

$elements = $xpath->query($expression);
echo "Found ", $elements->length, " elements:\n";
foreach ($elements as $index => $element) {
    printf(" #%02d: <%s>\n", $index, $element->tagName);
}

/**
 * Renames a node in a DOM Document.
 *
 * @param DOMElement $node
 * @param string     $name
 *
 * @return DOMNode
 */
function dom_rename_element(DOMElement $node, $name) {
    $renamed = $node->ownerDocument->createElement($name);

    foreach ($node->attributes as $attribute) {
        $renamed->setAttribute($attribute->nodeName, $attribute->nodeValue);
    }

    while ($node->firstChild) {
        $renamed->appendChild($node->firstChild);
    }

    return $node->parentNode->replaceChild($renamed, $node);
}

If you try it out, you might notice that now, after my answer, the number of heading elements has changed. I hope this is helpful!



来源:https://stackoverflow.com/questions/16307103/use-domdocument-to-replace-all-header-tags-with-the-h4-tags

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!