2013-04-05 40 views
1

解決方案 由於objective-c不編碼&(因爲它是保留的),您應該創建自己的方法。 來源:Sending an amp (&) using a post with Obj-CPHP file_get_contents分解爲&

對於我的iOS和Android應用程序,我使用php腳本來獲取一些數據。這個腳本有1個參數,這是一個鏈接。基本上,該腳本是這樣的:

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

$xml = new SimpleXMLElement($source); 

//Do stuff with the xml 

但是,當我把鏈接與&符號崩潰上的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! 

但完整的說法是

name_more_names_&_more_names_after_the_ampersand.file 

我試圖編碼在將它發送到file_get_contents之前沒有運氣的鏈接。

也試過:

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

具有相同的結果。

有誰知道它爲什麼會在&中斷?我不是Web開發人員,而是應用程序開發人員,因此我對這個主題缺乏瞭解。

編輯 也試過這樣:

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

這是結果:

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 

編輯#2

我發現爲什麼我的網址停在&符號。我檢索的URL我的論點用這種方法:

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

和_GET()與&符號權分離的論點?

+0

嘗試'進行urlencode( )'。 – BenM 2013-04-05 08:31:56

+0

已經嘗試過。沒有運氣 – 2013-04-05 08:32:53

回答

3

URL應該有它的連字符號正確編碼:

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

在PHP中,你可以編碼這樣的路徑:

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

更新

如果你也有一棵樹結構,你需要做更多的工作:

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

更新2

如果你的腳本被稱爲像script?link=<some-url>,你需要確保<some-url>被正確編碼太:

script?link=https%3A%2F%2Fwww.example.com%2Fxxxxx%2Fname_more_names_%26_more_names_after_the_ampersand.file 
+0

以及如何以編程方式在PHP中編碼&符號? urlencode()不是我正在尋找的方法。也不是utf_encode(); – 2013-04-05 08:37:16

+1

@MarkMolina,'php> echo urlencode(「&"); => %26' – Dogbert 2013-04-05 08:37:54

+0

你可以看看@我編輯的問題嗎? – 2013-04-05 08:45:40

0

使用

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