1

This works

$feed = $xml->xpath('//room[@id="103"]');

I am trying to replace 103 by a variable namely $id. I tried

$feed = $xml->xpath('//room[@id=$id]');

and

$feed = $xml->xpath('//room[@id=".$id."]');

None work.

What is the appropriate syntax for putting a variable in xpath?

2 Answers 2

2

When you writed $id in string, php use it like string. You should close quote like

$feed = $xml->xpath('//room[@id="'.$id.'"]');

Or write variable in {}

$feed = $xml->xpath('//room[@id="{$id}"]');
Sign up to request clarification or add additional context in comments.

1 Comment

$feed = $xml->xpath('//room[@id="'.$id.'"]'); this worked. The second one with curly brackets didn't. Thank you.
0

your question already answer from Mohammad but i give a more fully example with [0] at the end of the line to avoid more rows for some usages

$feed = $xml->xpath('//room[@id="'.$id.'"])[0];

also if you want result from xml with some others values inside to the root where use @attribute

$day= $_GET['Day']; 
$feed = $xml->xpath('//room[@id="'.$id.'"]/Day'.$day.'')[0];

this mean if you have a xml file like harder code you can cal a day dynamic

Comments

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.