Я хочу иметь отдельный PHP-класс, где хочу иметь функцию, которая вызывает API через cURL и получает ответ. Может ли кто-нибудь помочь мне в этом?
Спасибо.
Я хочу иметь отдельный PHP-класс, где хочу иметь функцию, которая вызывает API через cURL и получает ответ. Может ли кто-нибудь помочь мне в этом?
Спасибо.
просто используйте ниже фрагмент кода, чтобы получить ответ от спокойного URL-адреса веб-службы, я использую URL-адрес социального упоминания,
$response = get_web_page("http://socialmention.com/search?q=iphone+apps&f=json&t=microblogs&lang=fr");
$resArr = array();
$resArr = json_decode($response);
echo "<pre>"; print_r($resArr); echo "</pre>";
function get_web_page($url) {
$options = array(
CURLOPT_RETURNTRANSFER => true, // return web page
CURLOPT_HEADER => false, // don't return headers
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_MAXREDIRS => 10, // stop after 10 redirects
CURLOPT_ENCODING => "", // handle compressed
CURLOPT_USERAGENT => "test", // name of client
CURLOPT_AUTOREFERER => true, // set referrer on redirect
CURLOPT_CONNECTTIMEOUT => 120, // time-out on connect
CURLOPT_TIMEOUT => 120, // time-out on response
);
$ch = curl_init($url);
curl_setopt_array($ch, $options);
$content = curl_exec($ch);
curl_close($ch);
return $content;
}
Суть решения заключается в установке
CURLOPT_RETURNTRANSFER => true
затем
$response = curl_exec($ch);
CURLOPT_RETURNTRANSFER сообщает PHP хранить ответ в переменной вместо того, чтобы печатать его на странице, поэтому $response будет содержать ваш ответ. Вот ваш самый основной рабочий код (я думаю, не тестировал его):
// init curl object
$ch = curl_init();
// define options
$optArray = array(
CURLOPT_URL => 'http://www.google.com',
CURLOPT_RETURNTRANSFER => true
);
// apply those options
curl_setopt_array($ch, $optArray);
// execute request and get response
$result = curl_exec($ch);
Если кто-то еще сталкивается с этим, я добавляю другой ответ, чтобы предоставить код ответа или другую информацию, которая может потребоваться в "ответе".
http://php.net/manual/en/function.curl-getinfo.php
// init curl object
$ch = curl_init();
// define options
$optArray = array(
CURLOPT_URL => 'http://www.google.com',
CURLOPT_RETURNTRANSFER => true
);
// apply those options
curl_setopt_array($ch, $optArray);
// execute request and get response
$result = curl_exec($ch);
// also get the error and response code
$errors = curl_error($ch);
$response = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
var_dump($errors);
var_dump($response);
Выход:
string(0) ""
int(200)
// change www.google.com to www.googlebofus.co
string(42) "Could not resolve host: www.googlebofus.co"
int(0)
Конечная функция PHP curl:
function getURL($url,$fields=null,$method=null,$file=null){
// author = Ighor Toth <[email protected]>
// required:
// url = include http or https
// optionals:
// fields = must be array (e.g.: 'field1' => $field1, ...)
// method = "GET", "POST"
// file = if want to download a file, declare store location and file name (e.g.: /var/www/img.jpg, ...)
// please crete 'cookies' dir to store local cookies if neeeded
// do not modify below
$useragent = 'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko';
$timeout= 240;
$dir = dirname(__FILE__);
$_SERVER["REMOTE_ADDR"] = $_SERVER["REMOTE_ADDR"] ?? '127.0.0.1';
$cookie_file = $dir . '/cookies/' . md5($_SERVER['REMOTE_ADDR']) . '.txt';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true );
curl_setopt($ch, CURLOPT_ENCODING, "" );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt($ch, CURLOPT_AUTOREFERER, true );
curl_setopt($ch, CURLOPT_MAXREDIRS, 10 );
curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
curl_setopt($ch, CURLOPT_REFERER, 'http://www.google.com/');
if($file!=null){
if (!curl_setopt($ch, CURLOPT_FILE, $file)){ // Handle error
die("curl setopt bit the dust: " . curl_error($ch));
}
//curl_setopt($ch, CURLOPT_FILE, $file);
$timeout= 3600;
}
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout );
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout );
if($fields!=null){
$postvars = http_build_query($fields); // build the urlencoded data
if($method=="POST"){
// set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $postvars);
}
if($method=="GET"){
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
$url = $url.'?'.$postvars;
}
}
curl_setopt($ch, CURLOPT_URL, $url);
$content = curl_exec($ch);
if (!$content){
$error = curl_error($ch);
$info = curl_getinfo($ch);
die("cURL request failed, error = {$error}; info = " . print_r($info, true));
}
if(curl_errno($ch)){
echo 'error:' . curl_error($ch);
} else {
return $content;
}
curl_close($ch);
}