簡體   English   中英

如何在MediaWiki API中使用curl

[英]How to use curl with the 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);

但它不起作用,它給我布爾假為結果

這是一個使用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";

然后使用cookie進行登錄:

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

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM