Jump to content

Simple XML: Delete node by id


orionvictor

Recommended Posts

XML file:

 

<?xml version="1.0" ... >
<database xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <record>
        <id>1</id>
        <name></name>

    </record>
    <record>

        ...

    </record>
</database>

 

I want to delete the record where <id> equals $_GET['id']. I tried many suggested implementations based on xml or simplexml, without result.

Came across a very simple workaround (it should omit the record where id=$id), but can someone help me to taylor it to my xml scheme?

 

<?php
$file = "database.xml";

$id = $_GET['id'];
echo "DELETING: ".$id;
$xml = simplexml_load_file($file);

$str = "<?xml version=\"1.0\"?>
<database>";

foreach($xml->children() as $child){
if($child->getName() == "id") {
if($id == $child['name']) {
continue;
} else {
$str = $str.$child->asXML();
}
}
}
$str = $str."
</database>";
echo $str;

$xml->asXML("database_backup.xml");
$fh = fopen($file, 'w') or die("can't open file");
fwrite($fh, $str);
fclose($fh);
?>

Link to comment
https://forums.phpfreaks.com/topic/292954-simple-xml-delete-node-by-id/
Share on other sites

Using GET parameter as id

http://mysite.com/delete-xml-id.php?id=3

 

delete-xml-id.php

<?php
function delete_record($id, $file)
{
    $xml = new DOMDocument();
    $xml->load($file);
    
    $record = $xml->getElementsByTagName('record');
    foreach ($record as $person) {
        $person_id = $person->getElementsByTagName('id')->item(0)->nodeValue;
        //$person_name=$person->getElementsByTagName('name')->item(0)->nodeValue;
        if ($person_id == $id) {
            $id_matched = true;
            $person->parentNode->removeChild($person);
            
            break;
        }
    }
    if ($id_matched == true) {
        if ($xml->save($file)) {
            return true;
        }
    }
    
}


$file = "database.xml";
if (file_exists($file)) {
    if (isset($_GET['id']) && ctype_digit(trim($_GET['id']))) {
        $id = trim($_GET['id']);
        
        if (delete_record($id, $file)) {
            echo "$id removed";
        } else {
            echo "$id not removed";
        }
        
    } else {
        echo "id missing";
    }
} else {
    echo "$file missing";
}

?> 

database.xml

<?xml version="1.0" encoding="UTF-8"?>
<database xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<record>
    <id>1</id>
    <name>mark</name>
</record>
<record>
    <id>2</id>
    <name>bob</name>
</record>
<record>
    <id>3</id>
    <name>jane</name>
</record>
<record>
    <id>4</id>
    <name>mary</name>
</record>
<record>
    <id>5</id>
    <name>mary</name>
</record>
</database>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.