sophivorus / easy-wiki
MediaWiki Action API 的友好 PHP 客户端
v2
2024-01-15 16:10 UTC
Requires
- php: >=7.3
README
EasyWiki 是 MediaWiki Action API 的友好 PHP 客户端。
快速入门
composer require sophivorus/easy-wiki
require 'vendor/autoload.php'; // Connect to a MediaWiki Action API endpoint $api = new EasyWiki( 'https://en.wikipedia.org/w/api.php' ); // Read data immediately $wikitext = $api->getWikitext( 'Science' );
认证
如果您只想从公共维基(如维基百科)读取数据,则不需要认证,您可以继续到下一节。
但是,如果您想写入数据或从私有维基读取数据,您需要使用 机器人账户 进行认证。机器人账户是通过 Special:BotPasswords 创建的,这是通过 MediaWiki 安全机制的最简单方法。
// Be very careful not to publish your bot password by accident!!! $api->login( 'Your bot username', 'Your bot password' );
读取
// Get the wikitext of the page named 'Foo' $api->getWikitext( 'Foo' ); // Get the HTML of the page named 'Foo' $api->getHTML( 'Foo' ); // Get the categories of the page named 'Foo' $api->getCategories( 'Foo' );
如果没有可用的方法满足您的需求,您始终可以直接查询 API。EasyWiki 提供了方便的方法来完成此操作,并从结果中提取所需数据。请查看 MediaWiki Action API 文档 了解可用参数。
// Get the results as an associative array $data = $api->query( [ 'titles' => 'Foo', 'prop' => 'info' ] ); // Magically extract the desired piece of data from the gazillion wrappers $language = $api->find( 'pagelanguage', $query ); // If the result contains more than one relevant piece of data, you'll get an array of values instead $data = $api->query( [ 'titles' => 'Foo|Bar|Baz', 'prop' => 'info' ] ); $languages = $api->find( 'pagelanguage', $data ); foreach ( $languages as $language ) { echo $language; }
写入
// Create a page named 'Foo' with content 'Hello world!' $api->create( 'Foo', 'Hello world!' ); // Replace the content of the page named 'Foo' with 'Bye!' $api->edit( 'Foo', [ 'text' => 'Bye!' ] ); // Rename the page named 'Foo' to 'Bar' $api->move( 'Foo', 'Bar' ); // Delete the page named 'Bar' $api->delete( 'Bar' );
所有方法都有一个可选的最后一个参数,您可以在其中指定额外参数。例如
// Add a summary $api->create( 'Foo', 'Hello world!', [ 'summary' => 'My first edit!' ] ); // Mark the edit as minor $api->edit( 'Foo', 'Bye!', [ 'minor' => true ] ); // Don't leave a redirect behind and move all subpages too $api->move( 'Foo', 'Bar', [ 'noredirect' => true, 'movesubpages' => true ] );
架构
请查看 源代码 获取最终文档。
- 基本方法 是与 MediaWiki Action API 交互的基本构建块
get()
向 API 发送 GET 请求post()
向 API 发送 POST 请求find()
从结果中提取数据
- 操作方法 使用基本方法与 API 模块交互
login()
logout()
query()
parse()
edit()
move()
delete()
- 快捷方法 简化了常见请求
create()
append()
prepend()
getHTML()
getWikitext()
getCategories()
getPageInfo()
getSiteInfo()
getNamespaces()
getToken()
如果现有的任何方法都无法满足您的需求,您始终可以直接调用基本方法。