Я хочу использовать mediawiki api для получения некоторой информации с помощью проекта Symfony, я хочу использовать curl для вызовов API,
Я пробовал с
$ch=curl_init();
$postfield = "action=query&titles=Watch&prop=langlinks&lllimit=20";
$url = "https://en.wikipedia.org/w/api.php"; //url to wiki's api
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postfield);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
var_dump($output);
curl_close($ch);
но это не работает, это дает мне логическое ложное в результате
Вот хороший пример использования PHP API с использованием cURL из Викимедиа сам.
Сначала авторизируемся:
/**
* Configuration
* -------------------------------------------------
*/
// Start session
session_start();
// Login
$app['username'] = "Example";
$app['password'] = "mypassword";
// Version
$app["version"] = "0.0.1-dev";
// Last modified
date_default_timezone_set("UTC");
$app["lastmod"] = date("Y-m-d H:i", getlastmod()) . " UTC"; // Example: 2010-04-15 18:09 UTC
// User-Agent used for loading external resources
$app["useragent"] = "My First Tool " . $app["version"] . " (LastModified: " . $app["lastmod"] . ") Contact: myfirsttool (at) example (.) com";
// Cookie file for the session
$app["cookiefile"] = tempnam("/tmp", "CURLCOOKIE");
// cURL to avoid repeating ourselfs
$app["curloptions"] =
array(
CURLOPT_COOKIEFILE => $app["cookiefile"],
CURLOPT_COOKIEJAR => $app["cookiefile"],
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_USERAGENT => $app["useragent"],
CURLOPT_POST => true
);
$app["apiURL"] = "http://www.mediawiki.org/w/api.php";
Затем, чтобы войти, используя куки:
/**
* Login
* -------------------------------------------------
*/
// Info: http://www.mediawiki.org/wiki/API:Login
$postdata = http_build_query([
"action" => "login",
"format" => "php",
"lgname" => $app["username"],
"lgpassword" => $app["password"],
]);
$ch = curl_init();
curl_setopt_array($ch, $app["curloptions"]);
curl_setopt($ch, CURLOPT_URL, $app["apiURL"]);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
$result = unserialize(curl_exec($ch));
if(curl_errno($ch)){
$curl_error = "Error 003: " . curl_error($ch);
}
curl_close($ch);
//print_r($result);//die;//DEBUG
// Basic error check + Confirm token
if ($curl_error){
$domain_error = $curl_error;
} else if ($result["login"]["result"] == "NeedToken") {
if (!empty($result["login"]["token"])) {
$_SESSION["logintoken"] = $result["login"]["token"];
$postdata = http_build_query([
"action" => "login",
"format" => "php",
"lgname" => $app["username"],
"lgpassword" => $app["password"],
"lgtoken" => $_SESSION["logintoken"],
]);
$ch = curl_init();
curl_setopt_array($ch, $app["curloptions"]);
curl_setopt($ch, CURLOPT_URL, $app["apiURL"]);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
$result = unserialize(curl_exec($ch));
if(curl_errno($ch)){
$curl_error = "Error 004: " . curl_error($ch);
}
curl_close($ch);
//print_r($result);//die;//DEBUG
} else {
$other_error = "Error 006: Token error.";
}
}// Check for all documented errors
// Source: http://www.mediawiki.org/wiki/API:Login#Errors
// Date: 2010-04-17
if ($curl_error){
$domain_error = $curl_error;
} else if ($result["login"]["result"] == "Success") {
$_SESSION["login_result"] = $result["login"]["result"];
$_SESSION["login_lguserid"] = $result["login"]["lguserid"];
$_SESSION["login_lgusername"] = $result["login"]["lgusername"];
} else if ($result["login"]["result"] == "NeedToken") {
$other_error = "Error 005: Token error.";
} else if ($result["login"]["result"] == "NoName") {
$username_error = "The username can not be blank";
} else if ($result["login"]["result"] == "Illegal") {
$username_error = "You provided an illegal username";
} else if ($result["login"]["result"] == "NotExists") {
$username_error = "The username you provided doesn't exist";
} else if ($result["login"]["result"] == "EmptyPass") {
$password_error = "The password can not be blank";
} else if ($result["login"]["result"] == "WrongPass" || $result["login"]["result"] == "WrongPluginPass") {
$password_error = "The password you provided is incorrect";
} else if ($result["login"]["result"] == "CreateBlocked") {
$username_error = "Autocreation was blocked from this IP address";
} else if ($result["login"]["result"] == "Throttled") {
$other_error = "You've logged in too many times in a short time. Try again later.";
} else if ($result["login"]["result"] == "mustbeposted") {
$other_error = "Error 004: Logindata was not send correctly";
} else if ($result["login"]["result"] == "Blocked") {
$username_error = "This account is blocked.";
} else if ($result["login"]["result"]){
$other_error = "Error 001: An unknown event occurred.";
} else {
$other_error = "Error 002: An unknown event occurred.";
}
// The tool you use may log or display the variables:
// $other_error, $username_error and $password_error in the appropiate place
// Such as near a login form, or in a specific debug/logfile
// by default the errors are not outputted
if($_SESSION["login_result"] !== "Success"){
die("Login error. Have you defined app[username] and app[password] ?");
}
Пример построения запроса:
/**
* Get userinfo
* -------------------------------------------------
*/
$postdata = http_build_query([
"action" => "query",
"format" => "php",
"meta" => "userinfo",
"uiprop" => "rights|hasmsg",
]);
$ch = curl_init();
curl_setopt_array($ch, $app["curloptions"]);
curl_setopt($ch, CURLOPT_URL, $app["apiURL"]);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
$result = unserialize(curl_exec($ch));
if(curl_errno($ch)){
Death("Error 003: " . curl_error($ch),"API connection failed.");
}
curl_close($ch);
//print_r($result);//die;//DEBUG
// Check for usermessages
if (isset($result['query']['userinfo']['messages'])) {
$api['hasmsg'] = true;
$api['hasmsghtml'] = '<div class="usermessage">You have new messages !</div>';
} else {
// User does not have new messages
}
И, наконец, как очистить сессию:
// Delete the cookie file
unlink($app["cookiefile"]);
// Destroy the session
session_destroy();
// End this file
die($output);
Я попробовал это, и это тоже работает
public function callWiki($url)
{
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => 2
));
$result = curl_exec($ch);
curl_close($ch);
return $result;
}public function getAllCategories()
{
$api = 'https://en.wikipedia.org/w/api.php? action=query&titles=watch&prop=categories&format=json';
//get query result
$api_response = $this->callWiki($api);
$results = json_decode($api_response, true);
}