2014-01-16 24 views
2

我有一個來自$ _POST的數據數組,我想通過curl將它們發送到另一個頁面。如何序列化使用PHP的數組(數組到查詢字符串)

curl_setopt($s,CURLOPT_POST,true); 
curl_setopt($s,CURLOPT_POSTFIELDS,$this->_postFields); 

$this->_postFields必須像a=2&b=t正確的字符串?
因此,如果我想發送curl數據到另一個頁面我必須將數組轉換爲查詢字符串的權利?

我應該如何使用PHP?

♦我試過serialize()unserialize()但他們的格式與查詢字符串不一樣吧?
那我該怎麼辦? (我需要在jQuery中的.serialize()這樣的工作陣列不FORM)

♦目的地路徑不在我的控制之下,目的地的$ _POST應該是$ _POST而不是它的base64編碼,所以我可以'不要使用這樣的代碼。

$array = array(1,2,3); 
$encoded = json_encode($array); 
$decoded = json_decode($encoded); 
print_r($decoded); 

任何想法?

在此先感謝。

+0

如果問題不清楚,或者即使我應該刪除問題,請讓我知道。而不是僅僅把-1.thanks再次。 – ncm

+0

對於PHP解決方案,['http_build_query()'](http://us.php.net/manual/en/function.http-build-query.php)可能會有所幫助:[PHP函數將查詢字符串從Array](http://stackoverflow.com/questions/400805/php-function-to-build-query-string-from-array) – showdev

+0

@rafaelsoufraz - 謝謝但目的地路徑不在我的控制之下,$ _POST在目的地應該是$ _POST而不是它的base64編碼,所以我不能使用這樣的代碼.' $ array = array(1,2,3); $ encoded = json_encode($ array); $ decoded = json_decode($ encoded); print_r($ decode);' – ncm

回答

5

您可以使用http_build_query

curl_setopt($s, CURLOPT_POSTFIELDS, http_build_query($this->_postFields)); 

注意

它看起來美麗,但使用這種方法要小心下一個URL編碼。看:

$_POST["some value"]='value1'; // " " between 
$_POST["next value"]='value2'; // " " between 

$url = http_build_query($_POST); 

echo $url; 

// OUTPUT 
some+value=value1&next+value=value2 

當然,發送此$網址,我們不會得到預期從$ _ POST變量之後。

+0

+1 thanks.Please發表完整答案,我會接受你的 – ncm

+0

+ 1爲優秀的「gotcha」場景 – MonkeyZeus

+0

@MonkeyZeus - 我的英語不太好'gotcha'是什麼意思? – ncm

5

我認爲你可以只是這樣做:

curl_setopt($s, CURLOPT_POSTFIELDS, http_build_query($this->_postFields)); 
1

如果我明白了,你可以使用JSON。

$array = array(1,2,3); 
$encoded = json_encode($array); 
$decoded = json_decode($encoded); 
print_r($decoded); //Look to it 

如果不是它,可它:

$array = array(1,2,3); 
echo http_build_query($array); //Look to it