I have to make a new xml
using the value from another xml
. This is the xml
code. I tried using xpath
, but then I became confuse in order to display those value. Thanks for your help
<rss>
<item id='1234'>
<g:name>Gray</g:name>
<g:description>It's a Bag</g:description>
<g:detailed_images>
<g:detailed_image>abcd</g:detailed_image>
<g:detailed_image>abcde</g:detailed_image>
<g:detailed_image>abcdef</g:detailed_image>
</g:detailed_images>
</item>
<rss>
The new xml
format should be:
<rss>
<item>
<name></name>
<description></description>
<detailed_images>
<detailed_image></detailed_image>
<detailed_image></detailed_image>
</detailed_images>
</item>
</rss>
My bad, this is the php
code that is still in progress. I haven't really figure it all yet. I'm still new to xml too. :D
<?php
$document = new DOMDocument;
$document->preserveWhiteSpace = false;
$document->load('xml_edit_feeds.xml');
$xpath = new DOMXPath($document);
$xml = new DOMDocument;
$rss = $xml->appendChild($xml->createElement('rss'));
foreach ($xpath->evaluate('//item') as $item) {
//create tag item
$createItem = $rss->appendChild($xml->createElement('item'));
//getting item's attribute value
$valueID = $item->getAttribute('id');
//create attribute
$itemAttribute = $xml->createAttribute('id');
$itemAttribute->value = $valueID;
$createItem->appendChild($itemAttribute);
$result[] = [
'g:name' => $xpath->evaluate('string(g:name)', $item),
'g:description' => $xpath->evaluate('string(g:description)', $item),
'g:detailed_images' => $xpath->evaluate('string(g:detailed_images)', $item)
];
}
?>
It would be a lot clearer using SimpleXML, but as you've started with DOM, I will stick with it and base the answer on that.
$document = new DOMDocument;
$document->preserveWhiteSpace = false;
$document->load('xml_edit_feeds.xml');
$xpath = new DOMXPath($document);
$xml = new DOMDocument;
$rss = $xml->appendChild($xml->createElement('rss'));
foreach ($xpath->query('//item') as $item) {
//create tag item
$createItem = $rss->appendChild($xml->createElement('item'));
//getting item's attribute value
$valueID = $item->getAttribute('id');
//create attribute
$itemAttribute = $xml->createAttribute('id');
$itemAttribute->value = $valueID;
$createItem->appendChild($itemAttribute);
$description = $item->getElementsByTagName("description");
$descriptionE = $xml->createElement("description", $description[0]->nodeValue );
$createItem->appendChild($descriptionE);
$dImages = $item->getElementsByTagName("detailed_image");
$dImagesE = $xml->createElement("detailed_images");
$createItem->appendChild($dImagesE);
foreach ( $dImages as $image ) {
$img = $xml->createElement("detailed_image", $image->nodeValue );
$dImagesE->appendChild($img);
}
}
echo $xml->saveXML();
It is a case of extracting each piece of data from the original document (here picking the elements out by getElementsByTagName) and then creating the equivalent node in the new document.
With the images, this has to use a loop to add each image in one at a time.