Reputation: 23
I am trying to use a SimpleXML solution to find a specific value of a one child node to change another child node on the same level. I just tried to do it that way:
Can you help me how to make it properly in PHP?
This is my example XML:
<?xml version="1.0" encoding="utf-8" ?>
<products>
<product>
<local_id>1234</local_id>
<product_code>PRODUCT1</product_code>
<available>100</available>
<price>30</price>
</product>
<product>
<local_id>1235</local_id>
<product_code>PRODUCT2</product_code>
<available>50</available>
<price>45</price>
</product>
</products>
I know that I can do it in two different ways, but do not know which is more efficient.
Algorithm A:
I want to replace child-node <price>
(which is changing daily) with another value based on <local_id>
as below
<local_id> = 1235
<product>
with child-node found above<price>
) from 45 to i.e. 20Algorithm B:
Because one product with its ID has only one price I want to find a child-node <price>
on the same level as child-node <local_id>
and replace value as below
<local_id> = 1235
<price>
on the same level<price>
) from 45 to i.e. 20.I have searched everywhere, but some solutions are similar but not about my case (searching on the same level or finding parent based on child to find another child).
Thank you in advance!
PS - Question rebuilt to be more correct with rules and for clearance. Sorry for a mess at the beginning :)
Upvotes: 0
Views: 138
Reputation: 559
You should use $xml->xpath(), something like the following should work
$xmlstr ='<?xml version="1.0" encoding="utf-8" ?>
<products>
<product>
<local_id>1234</local_id>
<product_code>PRODUCT1</product_code>
<available>100</available>
<price>30</price>
</product>
<product>
<local_id>1235</local_id>
<product_code>PRODUCT2</product_code>
<available>50</available>
<price>45</price>
</product>
</products>';
$xml = new SimpleXMLElement($xmlstr);
$node = $xml->xpath('//products/product/local_id[text()="1235"]/parent::*')[0];
$node->price=99;
echo $xml->asXML();
In the above example, I replace the price value to verify that is the correct node.
Upvotes: 1