2013-07-01 114 views
5

我使用file_get_contents('php://input')檢索所有POST參數/從一個特定的網絡服務,例如值:解析結果(「PHP://輸入」)

$postText = file_get_contents('php://input'); 

導致這樣的事情:

inReplyToId=MG1133&to=61477751386&body=test&from=61477751386&messageId=166594397&rateCode= 

然後我需要得到每個單獨的鍵/值對的,因爲我需要將它們安置在一個新的數據庫記錄的字段。例如,我想結束:

$inReplyToId = MG1133 
$to = 61477751386 
$body = test 

一旦我知道了個人價值,我可以在數據庫中設置相應的字段。我通常會使用:

if(isset($_POST['inReplyToId']) && $_POST['inReplyToId'] !== '') { 
    $request->setField('_kf_GatewayMessageID', $_POST['inReplyToId']); 
} 

但因爲它不是正被提交application/x-www-form-urlencoded形式,將不會在這種情況下工作。

+2

['parse_str()'](http://ch2.php.net/manual/en/function.parse-str.php) – str

+1

http://www.php.net/manual/ en/function.parse-str.php – CBroe

+0

爲什麼使用'file_get_contents'和'php:// input'?在'INPUT_POST'或'serialize($ _ POST)'上使用[數據過濾器](http://www.php.net/manual/en/book.filter.php)會更好嗎?有什麼區別? –

回答

5

可以使用parse_str函數來分析查詢字符串:

$queryString = 'inReplyToId=MG1133&to=61477751386&body=test&from=61477751386&messageId=166594397&rateCode='; 
$data = array(); 
parse_str($queryString, $data); 
var_dump($data); 

Demo

編輯:

比如我想結束:

$inReplyToId = MG1133 
$to = 61477751386 
$body = test 

要獲得數組鍵作爲變量,你可以使用extract

extract($data); 

Demo

編輯2:如果你已經有一個使用$_POST與相應的指標,你可以合併數據變量的代碼它:

但修改這些變量我這是不可取的。

1

查看將參數化字符串轉換爲關聯數組的parse_str()函數。

0

您可以使用此代碼!嘗試!

<?php 
$postdata = file_get_contents("php://input"); 
//$postdata = '{"mail": "[email protected]", "number": 6969 }'; 

$obj = json_decode($postdata); 
echo $obj->{'mail'}; // [email protected] 

?>