2013-04-26 58 views
0

我已經設置了一個使用Nexmo API發送文本消息的PHP腳本,但是在編碼HTTP Get請求時存在問題。該腳本從存儲的數據中提取一些變量,然後觸發。我沒有使用PHP的經驗,並且已經花了很多時間在這上面,這是我的最後手段,任何人都可以看到我在下面的代碼中出錯了嗎?使用HTTP獲取請求的PHP URL編碼

該請求的預期格式:

https://rest.nexmo.com/sms/json?api_key=XXX&api_secret=XXX&to=XXX&from=XXX&text=XXX 

代碼:

function sendText() { 

    $api_key = $settings['consumer_key']; 
    $api_secret = $settings['consumer_secret']; 
    $recipient = $settings['recipient']; 
    $from = $settings['from']; 
    $text = $settings['sms_contents']; 

    $url = 'https://rest.nexmo.com/sms/json'; 
    $data = array_merge($data, array('api_key' => $api_key, 'api_secret' => $api_secret, 'to' => $recipient, 'from' => $from, 'text' => $text)); 

    $post = ''; 
    foreach($data as $k => $v){ 
     $post .= "&$k=$v"; 
    } 

    $opts = array('http' => 
      array(
       'method' => 'POST', 
       'header' => 'Content-type: application/x-www-form-urlencoded', 
       'content' => $post 
      ) 
     ); 
    $context = stream_context_create($opts); 
    $from_nexmo = file_get_contents($url, false, $context); 

    } 

sendText(); 

回答

0

嘗試使用urlencode()爲轉移值:

$post = array(); 

foreach($data as $k => $v){ 
    $post[] = $k . '=' . urlencode($v); 
} 

$post = implode('&', $post); 

$opts = array('http' => 
     array(
      'method' => 'POST', 
      'header' => 'Content-type: application/x-www-form-urlencoded', 
      'content' => $post 
     ) 
    ); 
+0

謝謝,這對我很有用。我感謝您的幫助! – 2013-04-26 05:33:37

+0

@傑瑞米休伊特,祝你好運。 – BlitZ 2013-04-26 05:35:39

1

我不認爲你正在做的任何編碼,這是我會做的:

foreach($data as $k => $v){ 
    $post .= "&$k=".urlencode($v); 
} 
0
Please try executing following code snippet 

function sendText() { 

$api_key = $settings['consumer_key']; 
$api_secret = $settings['consumer_secret']; 
$recipient = $settings['recipient']; 
$from = $settings['from']; 
$text = $settings['sms_contents']; 

$url = 'https://rest.nexmo.com/sms/json'; 
$data = array_merge($data, array('api_key' => $api_key, 'api_secret' => $api_secret, 'to' => $recipient, 'from' => $from, 'text' => $text)); 

$post=http_build_query($data); 

$opts = array('http' => 
     array(
      'method' => 'POST', 
      'header' => 'Content-type: application/x-www-form-urlencoded', 
      'content' => $post 
     ) 
    ); 
$context = stream_context_create($opts); 
$from_nexmo = file_get_contents($url, false, $context); 

} 
sendText();