0

I'm wanting to decrease the value of nodes which have a current value over a certain amount but can't seem to do it.

No errors are occurring but the nodes I want to affect aren't being updated.

Would anyone be able to point out what is wrong with the following:

$xml = '<?xml version="1.0"?>
<property>
<edited>true</edited>
<images>
<image>
<is_required><![CDATA[true]]></is_required>
<sorted_number><![CDATA[1]]></sorted_number>
</image>

<image>
<is_required><![CDATA[true]]></is_required>
<sorted_number><![CDATA[2]]></sorted_number>
</image>

<image>
<is_required><![CDATA[true]]></is_required>
<sorted_number><![CDATA[4]]></sorted_number>
</image>

<image>
<is_required><![CDATA[true]]></is_required>
<sorted_number><![CDATA[5]]></sorted_number>
</image>

</images>
</property>';

$sorted_target_number = 3;

foreach($xml->xpath('/property/images/image') as $tempImgNode){         
$s_number = $tempImgNode->sorted_number;
if ($s_number > $sorted_target_number) {
--$s_number;
}       
};

So image nodes with sorted_numbers of 4 and 5 would be changed to 3 and 4.

Thanks,

Mark

crooksy88
  • 3,849
  • 1
  • 24
  • 30

1 Answers1

1

The code you posted didn't run for sure. There's no SimpleXml object created.

$xml = simplexml_load_string($xml);

To do the subtraction, use the self-reference-technique:

$s_number[0] = $s_number - 1;

It allows updates of SimpleXml Elements as well as deletions: unset($node[0]). See more: https://stackoverflow.com/a/16062633/2016456

see it working: https://eval.in/536643

The operation above doesn't keep the CDATA though. If it is required, you need to take care of that with some extra steps, e.g. How to write CDATA using SimpleXmlElement? or use DOM.

Community
  • 1
  • 1
michi
  • 6,565
  • 4
  • 33
  • 56