以PHP詞條爲例,PHP先讀取:
http://zh.wikipedia.org/w/api.php?action=parse&format=xml&page=PHP
<text xml:space="preserve">下的內容,然後進行過濾,顯示到網頁上。
爲了方便測試,原內容保存到一個html中「wiki.html」
目前共有5篇帖子。
![]() |
以PHP詞條爲例,PHP先讀取:
http://zh.wikipedia.org/w/api.php?action=parse&format=xml&page=PHP <text xml:space="preserve">下的內容,然後進行過濾,顯示到網頁上。 爲了方便測試,原內容保存到一個html中「wiki.html」 ![]() ![]() |
![]() |
<?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> ![]() ![]() |
![]() |
輸出結果如下:
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月的... ![]() ![]() |
![]() |
PHP讀取維基百科服務器上的xml文件,可以用curl庫連接維基百科服務器並讀取xml文件內容,保存到一個變量中,然後用simplexml_load_file()函數讀取這個存有xml字符串的變量,讀取<text xml:space="preserve"></text>之間的內容,然後就可以繼續操作了。
![]() ![]() |
![]() |
PhpQuery貌似自帶了從其他服務器上獲取網頁類容的功能,也還帶有服務器端ajax功能,因此不需要自己再單獨寫curl網頁獲取代碼。
![]() ![]() |