Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a php variable in an xpath query

I want to use a php variable in an xpath statement. There is a similar thread here whose answer does not resolve my problem.

Here is example code (neither $r1 or $r2 create the intended array)

<?php
$xml = simplexml_load_file("menu.xml");
$term = "one";
$r1 = $xml->xpath("//category[@name=$term]");
$r2 = $xml->xpath("//category[@name=" . $term . "]");
$r3 = $xml->xpath("//category[@name='one']");

echo ('$r1 = '); print_r($r1);
echo ('<br>$r2 = '); print_r($r2);
echo ('<br>$r3 = '); print_r($r3);
?>

XML

<?xml version="1.0" encoding="ISO-8859-1"?>
<menu>
<category name="one">
    <item>Tomato and Cheese</item>
    <item>Onions</item>
    <item>Broccoli</item>
</category>
<category name="two">
    <item>Burger and Fries</item>
    <item>Chicken Sandwich</item>
</category>
<category name="three">
    <item>Filet of Fish</item>
    <item>Exotic Meat Stew</item>   
</category>

Output

$r1 = Array ( )
$r2 = Array ( ) 
$r3 = Array ( [0] => SimpleXMLElement Object ( [@attributes] => Array ( [name] => one ) [item] => Array ( [0] => Tomato and Cheese [1] => Onions [2] => Broccoli ) ) )

I'm probably missing something really simple but am stuck!

like image 349
vivanpc Avatar asked Sep 11 '25 23:09

vivanpc


2 Answers

You should add single quotes around the variables

$xml = simplexml_load_string($xml);
$term = "one";
$r1 = $xml->xpath("//category[@name='$term']");
$r2 = $xml->xpath("//category[@name='" . $term . "']");
$r3 = $xml->xpath("//category[@name='one']");

echo ('$r1 = '); print_r($r1);
echo ('<br>$r2 = '); print_r($r2);
echo ('<br>$r3 = '); print_r($r3);

Outputs

$r1 = Array ( [0] => SimpleXMLElement Object ( [@attributes] => Array ( [name] => one ) [item] => Array ( [0] => Tomato and Cheese [1] => Onions [2] => Broccoli ) ) )
$r2 = Array ( [0] => SimpleXMLElement Object ( [@attributes] => Array ( [name] => one ) [item] => Array ( [0] => Tomato and Cheese [1] => Onions [2] => Broccoli ) ) )
$r3 = Array ( [0] => SimpleXMLElement Object ( [@attributes] => Array ( [name] => one ) [item] => Array ( [0] => Tomato and Cheese [1] => Onions [2] => Broccoli ) ) ) 
like image 169
user20232359723568423357842364 Avatar answered Sep 13 '25 13:09

user20232359723568423357842364


Been a while since I've used xpath syntax, however, by deduction, it looks like the only diferrences the single quotes:

The follow are now equivalent.

$xml = simplexml_load_file("menu.xml");
$term = "one";
$r1 = $xml->xpath("//category[@name='$term']");
$r2 = $xml->xpath("//category[@name='" . $term . "']");
$r3 = $xml->xpath("//category[@name='one']");
like image 35
Jason McCreary Avatar answered Sep 13 '25 12:09

Jason McCreary