1

SOLUTION 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(https://www.example.com/xxxx/name_more_names_) [function.file-get-contents]: failed to open stream: HTTP request failed!

but the full argument is

name_more_names_&_more_names_after_the_ampersand.file

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.

EDIT Also tried this:

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

This is the result:

Warning: file_get_contents(https%3A%2F%2Fwww.example.com%2Fxxxxx%2Fname_more_names_) [function.file-get-contents]: failed to open stream: No such file or directory in

EDIT #2

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];
        }
        else
        {
            $lVariable = null;
        }
        return $lVariable;
    }

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

Community
  • 1
  • 1
Mark Molina
  • 5,057
  • 8
  • 41
  • 69

2 Answers2

3

The URL should have its ampersands properly encoded:

https://www.example.com/xxxx/name_more_names_%26_more_names_after_the_ampersand.file

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));

Update

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:

script?link=https%3A%2F%2Fwww.example.com%2Fxxxxx%2Fname_more_names_%26_more_names_after_the_ampersand.file
Kenster
  • 23,465
  • 21
  • 80
  • 106
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
0

Use

$url = urlencode($url);
$data = file_get_contents($url);