CodingForums.com

CodingForums.com (http://www.codingforums.com/index.php)
-   XML (http://www.codingforums.com/forumdisplay.php?f=3)
-   -   delete node in xml and database (http://www.codingforums.com/showthread.php?t=282285)

chumroo 11-15-2012 08:09 PM

delete node in xml and database
 
hi, i need some help about how to delete nodes in my xml file, here is my xml
Code:

<products>
  <product>
      <category>switch</category>
      <name>dgs105</name>
      <price>2000</price>
      <picture>networking/picture1.jpg</picture>
      <description>rapid to respond</description>
  </product>
  <product>
      <category>hub</category>
      <name>dlink</name>
      <price>1500</price>
      <picture>networking/picture4.jpg</picture>
    <description>ordinary</description>
  </product>
</products>

and this is my php code to delete the node and also in the database where the name correspond:
Code:

<?php

$category=$_POST['txt_category'];
$name=$_POST['txt_name'];

include("db_connect.php");

if($name!="" &&  $name!=null){
        $sql_delete="DELETE FROM products WHERE Category='$category' AND Name='$name'";
        $result = (mysql_query($sql_delete));
       

$xdoc = new DOMDocument();
$xdoc->load('../xml/addproductxml.xml');
$product=$xdoc->getElementsByTagName('product');
$findname=$xdoc->getElementsByTagName('name');
foreach ($findname as $node){
        $node->parentNode->removeChild($node);

}
$xdoc->save('../xml/addproductxml.xml');

}
?>

it does delete in my database but not in the xml and i cant really find the problem!! Please help

sunfighter 11-17-2012 03:35 PM

I have fallen in love with simplexml. It does everything you need to except delete a section of code. I found that out trying to answer this for you. I next went to the old DOMDocument method to delete but had trouble identifying the item number of the section I needed to delete. (There maybe a way of finding this in the doc, but I can't do it.) So I combined the two. First the simplexml to ID the section number by "category == "switch"" or something like it. and then using the dom to delete the section.

I did it by category == "switch" but you can use category == "name". simplexml is easy to use.

PHP Code:

<?php
$xml 
simplexml_load_file("products.xml");
$i 0;
foreach (
$xml as $category[])
{
    if(
$category[$i]->category == "switch")
        
$itemNumber $i;
    
$i++;
}

$xmlDOC = new DOMDocument();
$xmlDOC ->load('products.xml');
$YourElement $xmlDOC->documentElement ;
$Element2Remove $YourElement->getElementsByTagName('product')->item($itemNumber);

$oldContent $YourElement->removeChild($Element2Remove);
$xmlDOC->save("temp.xml"); // OR whatever file you want.
?>


chumroo 11-27-2012 07:32 AM

thank you very much sunfighter.... that was really of great help!! :)


All times are GMT +1. The time now is 08:09 PM.

Powered by vBulletin®
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.