PHP code example of zyan / u2p
1. Go to this page and download the library: Download zyan/u2p library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
zyan / u2p example snippets
use Zyan\U2P\U2P;
$u2p = new U2P();
// 输入网页链接,返回图片链接数组
$images = $u2p->get('https://mp.weixin.qq.com/s/-iRttNYNtn4z4qGGQ_fbvw');
print_r($images);
// [
// 'https://mmbiz.qpic.cn/.../640?wx_fmt=png&from=appmsg',
// 'https://mmbiz.qpic.cn/.../640?wx_fmt=png&from=appmsg&...',
// ...
// ]
$images = (new U2P())->get('https://mp.weixin.qq.com/s/xxxx');
use Zyan\U2P\Handlers\WeChatHandler;
$handler = new WeChatHandler();
$images = $handler->withCover()->handle('https://mp.weixin.qq.com/s/xxxx');
echo '封面图: ' . $images[0];
use Zyan\U2P\Handlers\GenericHandler;
$generic = new GenericHandler();
$images = $generic->handle('https://example.com/article');
use Zyan\U2P\AbstractHandler;
class ZhihuHandler extends AbstractHandler
{
public function supports(string $url): bool
{
return (bool) preg_match('#https?://www\.zhihu\.com/#i', $url);
}
public function handle(string $url): array
{
// 源码型:解析页面 HTML
$html = $this->fetch($url);
// ... 用 $this->loadDom($html) 解析
// ajax 型:抓接口 JSON 再解析
// $json = $this->fetch('https://www.zhihu.com/api/v4/...');
return $images;
}
}
$u2p = new U2P();
$u2p->registerHandler(new ZhihuHandler()); // 注册后优先匹配
$images = $u2p->get('https://www.zhihu.com/question/123456');
use Zyan\U2P\HttpClient;
use Zyan\U2P\U2P;
$client = new HttpClient(
['User-Agent' => 'MyBot/1.0', 'Cookie' => 'session=xxx'],
[CURLOPT_TIMEOUT => 60, CURLOPT_PROXY => 'http://127.0.0.1:7890']
);
$u2p = new U2P($client);
$images = $u2p->get('https://mp.weixin.qq.com/s/xxxx');
use Zyan\U2P\Handlers\WeChatHandler;
$handler = new WeChatHandler();
// 从已有 HTML 提取,不抓取网络
$images = $handler->extractContentImages($htmlString);
interface HandlerInterface
{
public function supports(string $url): bool; // 是否支持该链接
public function handle(string $url): array; // 返回图片链接数组
}
src/
├── U2P.php # 入口管理器
├── HandlerInterface.php # 处理器接口
├── AbstractHandler.php # 处理器基类
├── HttpClient.php # cURL 客户端
└── Handlers/
├── WeChatHandler.php # 微信公众号文章专项
└── GenericHandler.php # 通用兜底
tests/
├── WeChatHandlerTest.php # 单元测试
└── fixtures/wechat.html # 测试用的公众号 HTML 样本
docs/
└── test.php # 可运行示例