-1

I've got a problem with my xml parser, this is the xml file:

<?xml version="1.0" encoding="UTF-8"?>
<root name="gf">
  <node id="textone"/>
  <node id="textwo"/>
  <node id= "texthree" />
</root>

I use that code to parse the xml file:

       <?php
      $dom2 = new DOMDocument();
       $dom2->load('doc.xml');
       $xpath2 = new DOMXPath($dom2);
      $result2 = $xpath2->query('/root[@name="gf"]/node1/@id'); 

     $id2 = $result2->item(0)->nodeValue; //this contains the id that I must use

      $result2= $xpath2->query('/root[@name="gf"]/node1[@id='. $id2.']');
         $comp2 = $result2->item(0)->nodeValue;
     ?>

Why I got this error in the last row?? "Notice: Trying to get property of non-object" I've already used this code and when "id" it's a number it works, why it doesn't work when it's a string??

Mark
  • 141
  • 1
  • 3
  • 15
  • Not being entirely familiar with the syntax, this is a guess - but you're quoting the `gf` in `@name="gf"` - do you also need to quote the `@id` if it's a string? – andrewsi Feb 03 '16 at 16:11
  • @andrewsi sorry I've edited the xml, I need to quote id because in the xml tags are all "node" and I can't change them, I need to use the id – Mark Feb 03 '16 at 16:19
  • 1
    Sorry; I meant trying to change the second query to `'/root[@name="gf"]/node1[@id="'. $id2.'"]'`. If it's working with `$id2` is a number, but not a string, it might be because it needs to be quoted. – andrewsi Feb 03 '16 at 16:21
  • @andrewsi yesssss it works! thanks a lot mate! if you write it as answer I'll accept it :-) – Mark Feb 03 '16 at 16:25
  • Possible duplicate of [Php variable into a XML request string](http://stackoverflow.com/questions/27439368/php-variable-into-a-xml-request-string) – ThW Feb 03 '16 at 23:14

1 Answers1

1

If it works with integers, but not with strings, you probably just need to quote your variable in your query:

 $result2= $xpath2->query('/root[@name="gf"]/node1[@id="'. $id2.'"]');
andrewsi
  • 10,807
  • 132
  • 35
  • 51