0

just a quick question, was trying different ways to accomplish this, but ended with no success. I am trying to check attribute value using xpath and if the attribute value matches, I change the parameters for that tag in xml.

This works:

$obj= $xml->xpath('/document/item[@id = "a12sd"]');

This does not work, because I need to pass the value via a variable to check with the attribute value

$checkID = "a12sd";

$obj= $xml->xpath('/document/item[@id = $checkID]');

Any suggestions how I can rectify this problem.

EDIT:

XML File:

<?xml version="1.0" encoding="ISO-8859-1"?>
<document>
    <item id="a12sd">       
        <name>James</name>
        <pdf>0023.pdf</pdf>
    </item>
    <item id="rdf23">       
        <name>Alex</name>
        <pdf>0178.pdf</pdf>
    </item>
    <item id="2we34">       
        <name>Tom</name>
        <pdf>0886.pdf</pdf>
    </item>
    <item id="123de">       
        <name>Robby</name>
        <pdf>1239.pdf</pdf>
    </item>
</document>

PHP Code:

$id = "a12sd";
$xml = simplexml_load_file('items.xml');  

$who_is_who = $xml->xpath('/document/item[@id = "a12sd"]');             

$who_is_who[0]->name = "Arnold";

$xml->asXml("items.xml");

Thanks

4
  • Try putting the variable within quotes like you did on your first line: [@id = "$checkID"] Commented Jun 19, 2012 at 10:38
  • @Tino, did as you advised, but getting errors Commented Jun 19, 2012 at 10:41
  • It would be helpful to know which errors exactly ;) Commented Jun 19, 2012 at 10:43
  • Use $obj= $xml->xpath('/document/item[@id="'.$checkID.'"]'); Commented Jun 19, 2012 at 10:50

1 Answer 1

1

Try $obj= $xml->xpath('/document/item[@id="'.$checkID.'"]');

<?php
$id = "a12sd";
$xml = simplexml_load_file('items.xml');  

$who_is_who = $xml->xpath('/document/item[@id = "'.$id.'"]');             

$who_is_who[0]->name = "Arnold";

$xml->asXml("items.xml");

?>
Sign up to request clarification or add additional context in comments.

1 Comment

thanks Pushpesh, you saved my day one more time and I didn't realize it, that it can be done like that, thanks for pointing it out

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.