Tutorial for Working with XML Files in PHP
Let us assume the xml file as gallery1.xml with the data
1 2 3 4 5 6 7 8 9 10 11 12 13 | <?xml version=”1.0r43; encoding=”utf-8r43; standalone=”no”?> <gallery title=”TITLE CATEGORY”> <item title=”TITLE FOTO” picsmall=”image/category1/1_.jpg” picbig=”image/category1/1.jpg”> <![CDATA[Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Ipsum Lorem Ipsum Lorem Ipsum Ipsum Lorem Ipsum Lorem Ipsum Ipsum Lorem Ipsum Lorem Ipsum Ipsum Lorem Ipsum Lorem Ipsum Ipsum Lorem Ipsum Lorem Ipsum Ipsum Lorem Ipsum Lorem ]]> </item> <item title=”TITLE FOTO” picsmall=”image/category1/3_.jpg” picbig=”image/category1/3.jpg”> asdf </item> <item title=”TITLE FOTO” picsmall=”image/category1/3_.jpg” picbig=”image/category1/3.jpg”> <![CDATA[Lorem Ipsum……]]> </item> </gallery> |
Writing to XML file Dynamically
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | $xmldoc=”gallery1.xml”; $doc = new DOMDocument(); $doc->load($xmldoc); $doc->formatOutput = true; $root=$doc->getElementsByTagName(’gallery’)->item(0); //$r = $doc->createElement( “employees” ); //$doc->appendChild( $r ); $do1= $doc->createElement( “item” ); $att1=$do1->setAttribute(”title”,”junk”); $att2=$do1->setAttribute(”picsmall”,”image/category1/11.jpg”); $att3=$do1->setAttribute(”picbig”,”image/category1/11.jpg”); $do2=$doc->createCDATASection( “<h1> This is HighLight</h1>”); $do1->appendChild($do2); $root->appendChild( $do1 ); $doc->save($xmldoc); |
Reading XML files from PHP using DomDocument
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | $xmldoc=”gallery1.xml”; $doc = new DOMDocument(); $doc->formatOutput = true; $doc->load( $xmldoc ); $i=1; $searchNodes = $doc->getElementsByTagName(”item”); foreach( $searchNodes as $searchNode ) { $value= $searchNode->nodeValue; $valueID = $searchNode->getAttribute(’title’); $valueDate = $searchNode->getAttribute(’picsmall’); $valueAuthorID = $searchNode->getAttribute(’picbig’); echo “$value=====$valueID - $valueDate - $valueAuthorID<br>”; } |
Deleting XML nodes from XML file using DomDocument in PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | $xmldoc=”gallery1.xml”; $doc = new DOMDocument(); $doc->formatOutput = true; $doc->load( $xmldoc ); $i=1; $searchNodes = $doc->getElementsByTagName(”item”); foreach( $searchNodes as $searchNode ) { $value= $searchNode->nodeValue; if ($value === “asdf”) { echo “found the node”; $nud=$searchNode->parentNode; $nud->removeChild($searchNode); $doc->save($xmldoc); } } |
