如何在MediaWiki API中使用curl

时间:2016-08-02 08:49:32

标签: php curl mediawiki mediawiki-api

我想使用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);

但它不起作用,它给我布尔假为结果

2 个答案:

答案 0 :(得分:1)

以下是使用WikiMedia本身的cURL使用PHP API的一个很好的示例。

首先,登录:

/**
 *  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";

然后使用cookies进行登录:

/**
 *  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);

答案 1 :(得分:0)

我试过了,它可以正常工作

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

}