Why isn't my variable expanded on this line?

$q = $_GET['q'];

// Load and parse the XML document 

$rss =  simplexml_load_file('http://search.twitter.com/search.atom?lang=en&q=$q&rpp=100&page=1');

      

This returns results containing "$q"

instead of results containing value $q

. Why isn't it working?

+2


source to share


3 answers


Change your quotes to double quotes in the simplexml_load_file line

$q = $_GET['q'];

// Load and parse the XML document
$rss = simplexml_load_file("http://search.twitter.com/search.atom?lang=en&q=$q&rpp=100&page=1");

      



PHP will automatically resolve the variable only if the string is in double quotes.

+3


source


You need to use double quotes for variable expansion :

Variable parsing

When a string is specified in double quotes or with a heredoc, the variables are parsed within it.

So:

"http://search.twitter.com/search.atom?lang=en&q=$q&rpp=100&page=1"

      



But it would be even better if you use proper URL escaping with urlencode

:

'http://search.twitter.com/search.atom?lang=en&q='.urlencode($q).'&rpp=100&page=1'

      

You can also do this when you declare a variable $q

and then use a double quoted delimiter string:

$q = urlencode($_GET['q']);
$rss = simplexml_load_file("http://search.twitter.com/search.atom?lang=en&q=$q&rpp=100&page=1");

      

+1


source


Use double quotes instead of single quotes.

0


source







All Articles