diff options
author | Andres Rey <[email protected]> | 2017-11-26 19:41:27 +0000 |
---|---|---|
committer | Andres Rey <[email protected]> | 2017-11-26 19:41:27 +0000 |
commit | d984da4a263b26abd2690c55a965453bbf2e3e7c (patch) | |
tree | 93dfccb6ad093c6f6467361ddd1c64ec96f19099 /src | |
parent | fd8cb90dd2f6a3116b1f78cf51efbba52a7b3028 (diff) |
Add setNodeTag
Diffstat (limited to 'src')
-rw-r--r-- | src/NodeUtility.php | 41 |
1 files changed, 41 insertions, 0 deletions
diff --git a/src/NodeUtility.php b/src/NodeUtility.php index 8d412af..1d03e63 100644 --- a/src/NodeUtility.php +++ b/src/NodeUtility.php @@ -1,6 +1,9 @@ <?php namespace andreskrey\Readability; +use andreskrey\Readability\NodeClass\DOMDocument; +use andreskrey\Readability\NodeClass\DOMNode; +use andreskrey\Readability\NodeClass\DOMNodeList; /** @@ -28,4 +31,42 @@ class NodeUtility return $next; } + + + /** + * Changes the node tag name. Since tagName on DOMElement is a read only value, this must be done creating a new + * element with the new tag name and importing it to the main DOMDocument. + * + * @param string $value + * @param bool $importAttributes + * @return DOMNode + */ + public static function setNodeTag($node, $value, $importAttributes = false) + { + $new = new DOMDocument(); + $new->appendChild($new->createElement($value)); + + $children = $node->childNodes; + /** @var $children DOMNodeList $i */ + + for ($i = 0; $i < $children->length; $i++) { + $import = $new->importNode($children->item($i), true); + $new->firstChild->appendChild($import); + } + + if ($importAttributes) { + // Import attributes from the original node. + foreach ($node->attributes as $attribute) { + $new->firstChild->setAttribute($attribute->nodeName, $attribute->nodeValue); + } + } + + // The import must be done on the firstChild of $new, since $new is a DOMDocument and not a DOMElement. + $import = $node->ownerDocument->importNode($new->firstChild, true); + $node->parentNode->replaceChild($import, $node); + + return $import; + } + + }
\ No newline at end of file |