Skip to content

Instantly share code, notes, and snippets.

@ThomasWeinert
Created August 31, 2012 12:33
Show Gist options
  • Save ThomasWeinert/3552205 to your computer and use it in GitHub Desktop.
Save ThomasWeinert/3552205 to your computer and use it in GitHub Desktop.
Convert XML elements into text nodes including attribute values
<?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