2013-04-26 35 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();