gpt4 book ai didi

php - 如何使用参数和回调从 PHP 调用 JSON Web 服务?

转载 作者:搜寻专家 更新时间:2023-10-31 21:39:01 26 4
gpt4 key购买 nike

我从 JQuery $.getJSON 函数调用网络服务,它工作正常。

    var p = {
'field1': 'value1',
'field2': 'value2',
'field3': 'value3'
};

$.getJSON('https://service:xxx@xxx.xxx.yyyyy.com.xx/service/search?callback=?', p, function(data) {
if (data[0]) {
// print results
} else {
// no results found
}
});

我正在尝试从 PHP 和 CURL 进行连接,但是它不起作用,它总是返回 false。

//第一次尝试

$params = array(  'field1' => 'value1',  'field2' => 'value2', 'field3'=> 'value3');
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_URL, 'https://service:xxx@xxx.xxx.yyyyy.com.xx/service/search?callback=?');
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
$result = curl_exec($ch); // return false instead of my JSON

//第二次尝试

    $data_string = json_encode($params);                                                                                   
$ch = curl_init('https://https://service:xxx@xxx.xxx.yyyyy.com.xx/service/search?callback=?');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);

$result2 = curl_exec($ch); //return false instead of my JSON

我做错了什么?

非常感谢,

最佳答案

尝试将您的代码更改为:

$params = array(  'field1' => 'value1',  'field2' => 'value2', 'field3'=> 'value3');

$data_string = implode('&',$params);
//NB: you may need to urlencode the each of your params

$ch = curl_init('https://service:xxx@xxx.xxx.yyyyy.com.xx/service/search? callback=?&' .$data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result2 = curl_exec($ch);

未经测试的代码,希望对您有所帮助。

关于php - 如何使用参数和回调从 PHP 调用 JSON Web 服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13261929/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com