I have this test.xml:
<?xml version="1.0"?>
<Images>
<Image>
<Id>765</Id>
<Title>Img title 1</Title>
<Name>some_path_to_img.jpg</Name>
</Image>
</Images>
I try to append new '<Image>' to '<Images>', but without success.
Here is my code:
function update_xml_file() {
$xml = new DOMDocument();
$xml->load(file_get_contents('test.xml'));
$xml->formatOutput = true;
$base_node = $xml->getElementsByTagName('Images')->item(0);
$newimage = $xml->createElement("Image");
$img_id = $xml->createElement("Id");
$img_title = $xml->createElement("Title");
$img_name = $xml->createElement("Name");
$img_id->nodeValue = '766';
$img_title->nodeValue = 'Image title 2';
$img_name->nodeValue = 'some_path_to_img2.jpg';
$newimage->appendChild($img_id);
$newimage->appendChild($img_title);
$newimage->appendChild($img_name);
$base_node->appendChild($newimage);
umask();
$xml->save("test.xml");
}
Looking around for related discussions didn't help me.
Thanks for your time.
You have a little typo in the code which loads the xml data.
Change it to:
$xml->loadXML(file_get_contents('test.xml'));
or ( better)
$xml->load('test.xml');
Refer to the documentation of DOMDocument::loadXML() and DOMDocument::load()
You can also use this package from github to make it simple http://github.com/toureiliass/xdt
You can do it in a few line of code
$con = new XDT();
$con->connect('test.xml');
$con->getDocumentRootElement()->append('<image><id>765</id><title>some title</title><name>some_path_to_image.jpg</name></image>');
$con->save();
Related
php code creates xml and displays on screen. Unfortunately, I get an error and I don't know how to fix it.
This page contains the following errors:
error on line 2 at column 1: Extra content at the end of the document
Below is a rendering of the page up to the first error.
The structure of the xml file itself looks good after saving
<Movies>
<movie movie_id="5467">
<Title>The Campaign</Title>
<Year>2012</Year>
<Genre>The Campaign</Genre>
<Ratings>6.2</Ratings>
</movie>
</Movies>
I need to display the same code on screen after calling php.
$dom = new DOMDocument();
$dom->encoding = 'utf-8';
$dom->xmlVersion = '1.0';
$dom->formatOutput = true;
$xml_file_name = 'movies_list.xml';
$root = $dom->createElement('Movies');
$movie_node = $dom->createElement('movie');
$attr_movie_id = new DOMAttr('movie_id', '5467');
$movie_node->setAttributeNode($attr_movie_id);
$child_node_title = $dom->createElement('Title', '<![CDATA[The Campaign]]');
$movie_node->appendChild($child_node_title);
$child_node_year = $dom->createElement('Year', 2012);
$movie_node->appendChild($child_node_year);
$child_node_genre = $dom->createElement('Genre', '<![CDATA[The Campaign]]');
$movie_node->appendChild($child_node_genre);
$child_node_ratings = $dom->createElement('Ratings', 6.2);
$movie_node->appendChild($child_node_ratings);
$root->appendChild($movie_node);
$dom->appendChild($root);
Header('Content-type: text/xml');
echo $xml_file_name->asXML();
Please help me in solving. I looked for many solutions but nothing helped.
I need to read an XML file and delete all the elements named <images> and all the children associated. I have found similar old questions that did not work. What am I doing wrong? Is there a better method?
XML:
<?xml version='1.0' encoding='UTF-8'?>
<settings>
<background_color>#000000</background_color>
<show_context_menu>yes</show_context_menu>
<image>
<thumb_path>210x245.png</thumb_path>
<big_image_path>620x930.png</big_image_path>
</image>
<image>
<thumb_path>200x295.png</thumb_path>
<big_image_path>643x950.png</big_image_path>
</image>
</settings>
PHP:
$dom = new DOMDocument();
$dom->load('test.xml');
$thedocument = $dom->documentElement;
$elements = $thedocument->getElementsByTagName('image');
foreach ($elements as $node) {
$node->parentNode->removeChild($node);
}
$save = $dom->saveXML();
file_put_contents('test.xml', $save)
I figured it out after a good night of sleep. It was quite simple actually.
$xml = simplexml_load_file('test.xml');
unset($xml->image);
$xml_file = $xml->asXML();
$xmlFile = 'test.xml';
$xmlHandle = fopen($xmlFile, 'w');
fwrite($xmlHandle, $xml_file);
fclose($xmlHandle);
Edit: You probably want to make it save directly:
$file = 'test.xml';
$xml = simplexml_load_file($file);
unset($xml->image);
$success = $xml->asXML($file);
See SimpleXMLElement::asXML()Docs.
In the PHP Manual page (where you should always go 1st :-) one awesome contributor points out that:
You can't remove DOMNodes from a DOMNodeList as you're iterating over them in a foreach loop.
Then goes on to offer a potential solution. Try something like this instead:
<?php
$domNodeList = $domDocument->getElementsByTagname('p');
$domElemsToRemove = array();
foreach ( $domNodeList as $domElement ) {
// ...do stuff with $domElement...
$domElemsToRemove[] = $domElement;
}
foreach( $domElemsToRemove as $domElement ){
$domElement->parentNode->removeChild($domElement);
}
?>
First of all, your XML is broken, see <thumb>...</thumb_path>and next line as well -> fix it!
Then, real simple in 3 lines of code:
$xml = simplexml_load_string($x); // $x holds your xml
$count = $xml->image->count()-1;
for ($i = $count;$i >= 0;$i--) unset($xml->image[$i]);
See live demo # http://codepad.viper-7.com/HkGy5o
XML:
<?xml version="1.0" encoding="ISO-8859-1"?>
<root>
<pages>
<page><title>Home</title><content>Lorem Ipsum</content></page>
<page><title>Pictures</title><content>Lorem Ipsum</content></page>
<page><title>Information</title><content>Lorem Ipsum</content></page>
</pages>
<css>
<css-tag><title>background-color</title><value>#FFF</value></css-tag>
</css>
<layout>1</layout>
</root>
PHP:
$title = $_GET['0'];
$xml = new DOMDocument('1.0', 'ISO-8859-1');
$xml->formatOutput = true;
$xml->preserveWhiteSpace = true;
$xml->load($location);
$pages = $xml->getElementsByTagName("page");
foreach($pages as $page){
$pagetitle = $page->getElementsByTagName("title");
$pagetitlevalue = $pagetitle->item(0)->nodeValue;
if($title == $pagetitlevalue){
$pagetitle->item(0)->parentNode->removeChild($pagetitle->item(0));
}
}
$xml->save($location);
This code gets rid of just the <Title> node, how can it be changed to get rid of the parent <Page> node?
I can't figure out how to do this, I just manage to get rid of the title node and get loads of error codes
Whilst this is something I'd probably use xpath for, you can find...
$pagetitle->item(0)->parentNode->removeChild($pagetitle->item(0));
and replace with...
$pagetitle->item(0)->parentNode->parentNode->removeChild($pagetitle->item(0)->parentNode);
to go one level higher in your XML tree
I am creating xml file as below, can anybody help how to get that using php?
xml file:
<products>
<product id="123" />
</products>
Php file:
i am using following code but not getting result as above
$xml = new DomDocument('1.0', 'utf-8');
$xml->formatOutput = true;
$products= $xml->createElement('products');
$product = $xml->createElement('product');
$id = $xml->createElement('id');
$xml->appendChild($products);
$products->appendChild($product);
$product->appendChild($id);
$id->nodeValue = 123;
$xml->save("data.xml");
retrieving xml data:
$xml = new DomDocument();
$xmlFile = "data.xml";
$xml= DOMDocument::load($xmlFile);
$product = $xml->getElementsByTagName("product");
foreach($product as $node)
{
$address = $node->getElementsByAttributeName("address");
$address = $address->item(0)->nodeValue;
echo"$address";
}
You are not getting the results you want because you're adding id as a tag rather than an attribute. I just refactored your code a little and made id an attribute. I tested the code below and it produces your desired result.
<?php
$xml = new DomDocument('1.0', 'utf-8');
$xml->formatOutput = true;
$products= $xml->createElement('products');
$product = $xml->createElement('product');
$xml->appendChild($products);
$products->appendChild($product);
$product->appendChild(new DomAttr('id', '123'));
$xml->save("data.xml");
?>
If id is to be an attribute, then you need to use the DOMElement::setAttribute() method. I think this will work - according to the documentation, if an attribute doesn't already exist it will be created.
$product->setAttribute("id", "123");
Then loas the $product->appendChild( $id );
here i am creating xml file dynamically at run time but i m getting error
XML Parsing Error: junk after document element
Location: http://localhost/tam/imagedata.php?imageid=8
Line Number 9, Column 1:
^
$id=$_GET['imageid'];
$dom = new DomDocument('1.0');
$query="select * from tbl_image_gallery where imageId='$id'";
$select=mysql_query($query);
while($res=mysql_fetch_array($select))
{
$content = $dom->appendChild($dom->createElement('content'));
$image = $content->appendChild($dom->createElement('image'));
$small_image_path = $image->appendChild($dom->createElement('small_image_path'));
$small_image_path->appendChild($dom->createTextNode("load/images/small/".$res['image']));
$big_image_path = $image->appendChild($dom->createElement('big_image_path'));
$big_image_path->appendChild($dom->createTextNode("load/images/big/".$res['image']));
$description = $image->appendChild($dom->createElement('description'));
$description->appendChild($dom->createTextNode($res['description']));
$dom->formatOutput = true;
}
echo $test1 = $dom->saveXML();
and xml format is
<?xml version="1.0"?>
<content>
<image>
<small_image_path>load/images/small/1.jpg</small_image_path>
<big_image_path>load/images/big/1.jpg</big_image_path>
<description>hgjghj</description>
</image>
<image><small_image_path>load/images/small/2.jpg</small_image_path><big_image_path>load/images/big/2.jpg</big_image_path><description>fgsdfg</description></image><image><small_image_path>load/images/small/3.jpg</small_image_path><big_image_path>load/images/big/3.jpg</big_image_path><description>sdfgsdfg</description></image><image><small_image_path>load/images/small/4.jpg</small_image_path><big_image_path>load/images/big/4.jpg</big_image_path><description>gsbhsg</description></image><image><small_image_path>load/images/small/4.jpg</small_image_path><big_image_path>load/images/big/4.jpg</big_image_path><description>gsbhsg</description></image><image><small_image_path>load/images/small/avatar.jpg</small_image_path><big_image_path>load/images/big/avatar.jpg</big_image_path><description></description></image></content>
Can it be that you are posting html code into the description field?
Could be usefull to add a CDataSection instead of a TextNode
$cdata = $dom->createCDATASection($res['description']);
$image->appendChild($cdata);