Page 1 of 1

passing a php variable to an xpath

Posted: Tue Sep 23, 2008 9:08 am
by cgoasduff
HI there

I am trying to pass a variable to an xpath expression

the value comes from a url ex: mysite.com/page.php?ids=2

When I hardcode the value in the Xpath

Code: Select all

$siteID = $xml->xpath('//blackboard/site[id="2"]/image');
it works ok

If try to get the value from the variable

Code: Select all

$siteID = $xml->xpath('//blackboard/site[id="$val"]/image'); 
 
it just doesn't work

Here is my code:

Code: Select all

 
$val = $_GET['ids'];
    echo "the value is: $val"; 
    
    
    $xml = simplexml_load_file('blackboard.xml');
        $siteID = $xml->xpath('//blackboard/site[id="$val"]/image'); 
        foreach($siteID as $image) { }
    ?> 
 
<img src="http://localhost/frogvisionjuly08/images/<?php echo "$image"; ?>" />
 
and the XML document format

Code: Select all

 
 
<blackboard>
   <site> 
 
    <id>1</id>
    <image>sites/stevenson.png</image>
    <text>Stevenson's website</text>
  </site>
 
  <site> 
  <id>2</id>
    <image>sites/sophie/sophie.jpg</image>
    <text>Sophie's webiste</text>
  </site>
</blackboard>
 

Thanks for looking

Chris










I have an xml document formated that way

Code: Select all

<blackboard>
  <site> 
  <id>2</id>
    <image>sites/sophie/sophie.jpg</image>
    <text>Sophie Mckay Knight's website </text>
  </site>
  <site> 
    <id>1</id>
    <image>sites/stevensonMarshall/blackboard.png</image>
    <text>Stevenson and Marshall</text>
  </site>
  </blackboard>

Re: passing a php variable to an xpath

Posted: Tue Sep 23, 2008 9:14 am
by Maugrim_The_Reaper
Have you tried concatenation?

Code: Select all

'//blackboard/site[id="' . "$val" . '"]/image'

Re: passing a php variable to an xpath

Posted: Tue Sep 23, 2008 9:38 am
by cgoasduff
Thanks a lot.. it now works!

Re: passing a php variable to an xpath

Posted: Wed Oct 01, 2008 1:04 am
by cujo
Hi, Paddy! We've had email conversation about phpspec some time ago, glad to meet u again :-)

I have the same problem - passing variables into xpath. Concatination for some reasons is not the way to go and besides, it won't help when we need to pass in variable Node or NodeList.

It seems that DOM extension just doesn't support it, so threre is no chanses, am I right?