0

我已经设置了一个 PHP 脚本来使用 Nexmo API 发送文本消息,但是我对 HTTP Get 请求的编码方式存在问题。该脚本从存储的数据中提取一些变量,然后触发。我没有使用 PHP 的经验,并且已经花了很多时间,这是我最后的手段,有没有人能看到我在下面的代码中哪里出错了?

请求的预期格式:

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();
4

3 回答 3

1

我不认为你在做任何编码,这就是我要做的:

foreach($data as $k => $v){
    $post .= "&$k=".urlencode($v);
}
于 2013-04-26T04:41:31.847 回答
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
        )
    );
于 2013-04-26T04:41:22.563 回答
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();
于 2013-04-26T05:30:39.340 回答