Mark Molina Mark Molina - 11 months ago 104
PHP Question

PHP file_get_contents breaks up at &

Because objective-c doesn't encode & (because it is reserved) you should create your own method.
Source: Sending an amp (&) using a post with Obj-C

For my iOS and Android app I use a php script to get some data. This script has 1 argument which is a link. Basically that script looks like this:

$link= urlVariable('link');
$source = file_get_contents($link);

$xml = new SimpleXMLElement($source);

//Do stuff with the xml

But when I send a link with the & symbol it crashes on file_get_contents

Warning: file_get_contents( [function.file-get-contents]: failed to open stream: HTTP request failed!

but the full argument is


I tried encoding the link before sending it to file_get_contents with no luck.

Also tried:

function file_get_contents_utf8($fn) {
$content = file_get_contents($fn);
return mb_convert_encoding($content, 'UTF-8',
mb_detect_encoding($content, 'UTF-8, ISO-8859-1', true));

with the same results.

Does anybody know why it breaks at &? I'm no web developer but an app developer so excuse me for the lack of knowledge on this subject.

Also tried this:

$link= urlVariable('link');
$encodedLink = urlencode($link);
$source = file_get_contents($encodedLink);

This is the result:

Warning: file_get_contents( [function.file-get-contents]: failed to open stream: No such file or directory in


I found why my url stops at the & symbol. I retrieve my argument from the url with this method:

function urlVariable($pVariableName)
if (isset ($_GET[$pVariableName]))
$lVariable = $_GET[$pVariableName];
$lVariable = null;
return $lVariable;

and _GET() separates arguments with the & symbol right?

Answer Source

The URL should have its ampersands properly encoded:

In PHP you can encode the path like this:

$path = parse_url($url, PHP_URL_PATH);
$url = substr_replace($url, '/' . urlencode(substr($path, 1)), strpos($url, $path), strlen($path));


If you also have a tree structure, you would need to do more work:

$path = parse_url($url, PHP_URL_PATH);
$newpath = '/' . str_replace('%2F', '/', urlencode(substr($path, 1)));

$url = substr_replace($url, $newpath, strpos($url, $path), strlen($path));

Update 2

If your script is called like script?link=<some-url>, you need to make sure the <some-url> is properly encoded too: