Created
August 31, 2012 12:33
-
-
Save ThomasWeinert/3552205 to your computer and use it in GitHub Desktop.
Convert XML elements into text nodes including attribute values
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$data = <<<XML | |
<?xml version="1.0" encoding="ISO-8859-1"?> | |
<element> | |
<title>ein Titel</title> | |
<content>Ein Inhalt</content> | |
<content> | |
Ein Inhalt mit | |
<subcontent att1="Hallo">Subnodes</subcontent> und weiterem Text, | |
der <subcontent att1="Hallo" att2="Welt" > weitere Subnodes enthalten</subcontent> | |
kann | |
</content> | |
</element> | |
XML; | |
$dom = new DOMDocument(); | |
$dom->loadXml($data); | |
$xpath = new DOMXpath($dom); | |
// let's look for all subcontent elements in all or no namespaces | |
foreach ($xpath->evaluate('//*[local-name() = "subcontent"]') as $contentNode) { | |
$text = ''; | |
// all attribute values to a string | |
foreach ($contentNode->attributes as $attribute) { | |
$text .= $attribute->value.' '; | |
} | |
// add the text content of the node | |
$text .= $contentNode->textContent; | |
// and create a text node from that string | |
$textNode = $dom->createTextNode($text); | |
//replace the element with the new text node | |
$contentNode->parentNode->replaceChild( | |
$textNode, $contentNode | |
); | |
} | |
header('Content-type: text/xml'); | |
echo $dom->saveXml(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment