1

My xml looks like this:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<images>
    <pic>
        <image>54</image>
        <descr>Image 1</descr>
    </pic>
    <pic>
        <image>32</image>
        <descr>Image 2</descr>
    </pic>
    <pic>
        <image>47</image>
        <descr>Image 3</descr>
    </pic>
</images>

I want to remove one element, for example second pic (image 32). Using this code, but it's not working.

$xml = simplexml_load_file('../../images.xml');

$target = false;
$i = 0;
foreach ($xml->pic as $m) {
  if ($m['image']=='32') { $target = $i; break; }
  $i++;
}
if ($target !== false) {      //$target always be $false
  unset($xml->pic[$target]);
}

echo $xml->savexml();

Thanks for any advice.

3 Answers 3

1

Observations

$m is object not array so $m['image'] should be changed to $m->image

Change $target = false; to $target = 0 ;

Example

$xml = simplexml_load_file ( '1.xml' );
$target = 0;
$i = 0;
foreach ( $xml->pic as $m ) {
    if ($m->image == '32') {
        $target = $i;
        break;
    }
    $i ++;
}

if ($target !== false) {
    unset ( $xml->pic [$target] );
}
echo $xml->savexml ();
Sign up to request clarification or add additional context in comments.

2 Comments

This will not work. His original test for target was fine - this code will always delete the 2nd pic.
+1 thanks @Sam Dufel .. just notice the dependency on $i change my script
0

Your test is wrong

if ($target !== false) { 

should be

if ($target > 0) { 

2 Comments

!== tests for same value AND type. 0 is never !== false (boolean and int).
Reread his code. He's initializing target to false, and setting it to an integer value when he finds the correct index. If target === false, the correct index was never found. Otherwise, target has been set to the index of the element he's deleting (and 0 is a valid index).
0

Try creating a new XML object, and add only the data you want and save the new object.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.