passing a php variable to an xpath

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
cgoasduff
Forum Newbie
Posts: 6
Joined: Thu Jun 28, 2007 3:21 am

passing a php variable to an xpath

Post 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>
User avatar
Maugrim_The_Reaper
DevNet Master
Posts: 2704
Joined: Tue Nov 02, 2004 5:43 am
Location: Ireland

Re: passing a php variable to an xpath

Post by Maugrim_The_Reaper »

Have you tried concatenation?

Code: Select all

'//blackboard/site[id="' . "$val" . '"]/image'
cgoasduff
Forum Newbie
Posts: 6
Joined: Thu Jun 28, 2007 3:21 am

Re: passing a php variable to an xpath

Post by cgoasduff »

Thanks a lot.. it now works!
cujo
Forum Newbie
Posts: 1
Joined: Wed Oct 01, 2008 12:47 am

Re: passing a php variable to an xpath

Post 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?
Post Reply