作者共发了5篇帖子。 内容转换:不转换▼
 
点击 回复
208 4
[示例]phpQuery過濾維基百科內容
一派护法 十九级
1楼 发表于:2015-2-26 15:01
以PHP詞條爲例,PHP先讀取:
http://zh.wikipedia.org/w/api.php?action=parse&format=xml&page=PHP
<text xml:space="preserve">下的內容,然後進行過濾,顯示到網頁上。

爲了方便測試,原內容保存到一個html中“wiki.html”
一派护法 十九级
2楼 发表于:2015-2-26 15:01
<?php
mb_internal_encoding("UTF-8"); // encoding for mbstring
include 'phpQuery-onefile.php';
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>DOM</title>
</head>
 
<body>
<?php
$doc = phpQuery::newDocumentFileHTML("wiki.html");

$doc["table"]->remove(); // remove tables as well as their contents
$doc[":header"]->remove(); // remove <h1>-<h6>
$doc["#coordinates"]->remove(); // remove the float layer 'coordinates'
$doc["span.editsection"]->remove(); // remove Links 'edit'
$doc["small"]->remove();
// remove <span> but keep its content
foreach ($doc["span"] as $span) {
    $span = pq($span);
    $span->after($span->text())->remove();
}
$doc["div"]->remove();
$doc["script"]->remove();

// remove [number]
foreach ($doc["a"] as $a) {
    $a = pq($a);
    if (preg_match("/^\\[\\d+\\]$/", trim($a->text()))) {
        $a->remove();
    }
}

$doc->html($doc->text()); // remove all other html labels

$html = $doc->html();
$html = preg_replace("/\\n{2,}/", "\n", $html); // \n\n\n\n\n => \n

define("MAXLEN", 400);
$shortened = false;
if (mb_strlen($html) > MAXLEN) {
    $html = mb_substr($html, 0, MAXLEN);
    $shortened = true;
}

$html = preg_replace("/^[\\n\\s]+/", "", $html); // remove \n\s\n\s\n\s at the beginning
$html = preg_replace("/[\\n\\s]+$/", "", $html); // remove \n\s\n\s\n\s at the end
$html = preg_replace("/\\n/", "<br>", $html); // \n => <br>
if ($shortened) {
    $html .= "...";
}
$doc->html($html);



echo $doc->html();
?>
</body>
</html>
一派护法 十九级
3楼 发表于:2015-2-26 15:02
輸出結果如下:
PHP(全称:PHP:Hypertext Preprocessor,即“PHP:超文本预处理器”)是一种开源的通用计算机脚本语言,尤其适用于网络开发并可嵌入HTML中使用。PHP的语法借 鉴吸收C语言、Java和Perl等流行计算机语言的特点,易于一般程序员学习。PHP的主要目标是允许网络开发人员快速编写动态页面,但PHP也被用于 其他很多领域。
PHP最初是由勒多夫在1995年开始开发的。而現在PHP的標準由PHP Group和開放原始碼社群維護。PHP以PHP License作為許可協議,不過因為這個協議限制了PHP名稱的使用,所以和開放原始碼許可協議GPL不相容。
PHP的應用範圍相當廣泛,尤其是在網頁程式的開發上。一般來說PHP大多執行在網頁伺服器上,透過執行PHP程式碼來產生使用者瀏覽的網頁。PHP可以在多數的伺服器和作業系統上執行,而且使用PHP完全是免費的。根據2013年4月的...
一派护法 十九级
4楼 发表于:2015-2-26 15:09
PHP讀取維基百科服務器上的xml文件,可以用curl庫連接維基百科服務器並讀取xml文件內容,保存到一個變量中,然後用simplexml_load_file()函數讀取這個存有xml字符串的變量,讀取<text xml:space="preserve"></text>之間的內容,然後就可以繼續操作了。
一派护法 十九级
5楼 发表于:2015-2-27 23:27
PhpQuery貌似自帶了從其他服務器上獲取網頁類容的功能,也還帶有服務器端ajax功能,因此不需要自己再單獨寫curl網頁獲取代碼。

回复帖子

内容:
用户名: 您目前是匿名发表
验证码:
(快捷键:Ctrl+Enter)
 

本帖信息

点击数:208 回复数:4
评论数: ?
作者:巨大八爪鱼
最后回复:巨大八爪鱼
最后回复时间:2015-2-27 23:27
 
©2010-2024 Arslanbar Ver2.0
除非另有声明,本站采用知识共享署名-相同方式共享 3.0 Unported许可协议进行许可。