How to use file_get_contents to get a URL with query string attached

I found today the PHP file_get_contents function does not work with URLs containing a query string with spaces in it. The following code example should say it all:

<p>Shows how spaces in url’s query string do not work with file_get_contents, but replacing spaces with + does work</p>
results of code block one:<br />
<?php
$url = “http://sportsweatherstats.com/test/showurl.php?u=this and that&h=that and this”;
$html = file_get_contents($url);
echo $html;
?>

results of code block two:<br />

<?php
$url = “http://sportsweatherstats.com/test/showurl.php?u=this+and+that&h=that+and+this”;
$html = file_get_contents($url);
echo $html;
?>

CLICK HERE TO RUN THE ABOVE CODE

Summary

when you run the code above, you will notice that the first block of code runs but only returns partial results while the second block  returns complete results because we replaced spaces in the query string with plus signs. I hope this helps someone else.

Leave a Reply

Your email address will not be published. Required fields are marked *