想自動查詢成語釋義?洪恩線上成語詞典(study.hongen.com)提供豐富的成語資料,但缺乏公開 API。本文示範如何用 PHP 打造一個輕量級爬蟲,核心採用 file_get_contents 取得遠端頁面,並解決編碼轉換與 HTML 切片的關鍵細節。
洪恩查詢介面要求傳遞的成語關鍵字必須經過 JavaScript escape() 編碼。PHP 沒有內建相同函式,需自行實作:
<?php
function escape($str) {
preg_match_all('/[\x80-\xff].|[\x01-\x7f]+/', $str, $r);
$ar = $r[0];
foreach ($ar as $k => $v) {
if (ord($v[0]) < 128) {
$ar[$k] = rawurlencode($v);
} else {
$ar[$k] = '%u' . bin2hex(iconv('GB2312', 'UCS-2', $v));
}
}
return join('', $ar);
}
?>
此函式將字串拆解為單字元或多位元組序列,ASCII 字元用 rawurlencode,非 ASCII 字元轉為 %uXXXX 格式,完整模擬 JS escape 行為。
<?php
function chacy($chengyu) {
$chengyu = escape($chengyu);
$url = 'https://study.hongen.com/dict/ndsearchchengyu.aspx?type=exact&word=' . $chengyu;
$text = @file_get_contents($url);
// 只保留主要內容區塊
$pos1 = strpos($text, '<table class="root">');
$pos2 = strrpos($text, '<table class="english">');
$text = substr($text, $pos1, $pos2 - $pos1);
// 編碼轉換:洪恩回傳 UTF-8,轉為 GB2312 並忽略非法字元
$text = iconv('UTF-8', 'GB2312//IGNORE', $text);
// 以「出處」字樣判斷是否成功取得資料
if (strpos($text, '出處')) {
return $text;
}
return false;
}
?>
關鍵說明:
strpos/strrpos 定位兩個 <table> 標籤,精準切出成語釋義區塊(含拼音、釋義、出處、例句)。iconv 後附加 //IGNORE,避免遇到特殊字元(如漢字「一」)導致轉換中斷。<?php
require_once 'chengyu_func.php'; // 假設上述函式存放於此檔案
$keyword = '畫蛇添足';
$result = chacy($keyword);
if ($result) {
echo $result; // 直接輸出 HTML 片段,可嵌入頁面
} else {
echo '查無此成語或擷取失敗';
}
?>
原始碼出處:凡人博客原創,轉載請註明。