2011-01-27 59 views
21

使用PHP簡單的HTML DOM解析器時,是否正常換行
標籤被剝離?保留換行符 - 簡單的HTML DOM解析器

+2

使用內置的dom解析器,而不是簡單的html dom。內置的解析器速度提高了一個數量級。 http://whitlock.ath.cx/FastCrawl/benchmark.php – 2011-01-27 04:29:29

+4

對不起,@ByronWhitlock,但我不使用簡單的HTML DOM解析器的速度,我用它來做很多事情,我根本無法做的DOMDocument,而且它更容易!但是,OH <我爲Simple PHP DOM解析器的PHP擴展版本所做的工作! – 2012-07-06 18:02:17

回答

19

也很苦惱,因爲我需要HTML在處理後很容易編輯。

顯然有在SimpleHTMLDOM腳本$stripRN一個布爾值,這是設置爲true上默認。它將HTML中的\r\n\r\n標籤剝離。

將var設置爲false(在腳本中出現了幾處),並解決了您的問題。

+0

感謝這個答案,你只是保存了一天:D – mingos 2011-10-24 11:28:25

+3

我**真**希望這被記錄在他們的網站上。隊友的歡呼聲! – 2012-07-06 18:02:47

2

您不必改變所有$stripRN爲false,影響此行爲的唯一一個是線816``:

// load html from string 
function load($str, $lowercase=true, $stripRN=false, $defaultBRText=DEFAULT_BR_TEXT) { 

還要考慮改變線路988,因爲多字節的功能往往不安裝在不涉及非西歐語言的機器上。在V1.5原始換行符立即腳本:

if (function_exists('mb_detect_encoding')) { $charset = mb_detect_encoding($this->root->plaintext . "ascii", $encoding_list = array("UTF-8", "CP1252")); } else $charset === false; 
46

我知道這是老了,但我一直在尋找這樣的歡迎,並意識到有實際上是一個內置的選項關閉移除管線斷裂。無需編輯源代碼。

的PHP簡單的HTML DOM解析器的load功能支持多種有用的參數:

load($str, $lowercase=true, $stripRN=false, $defaultBRText=DEFAULT_BR_TEXT) 

當調用load功能,只需通過false作爲第三個參數。

$html = new simple_html_dom(); 
$html->load("<html><head></head><body>stuff</body></html>", true, false); 

如果使用file_get_html,這是第九個參數。

file_get_html($url, $use_include_path = false, $context=null, $offset = -1, $maxLen=-1, $lowercase = true, $forceTagsClosed=true, $target_charset = DEFAULT_TARGET_CHARSET, $stripRN=true, $defaultBRText=DEFAULT_BR_TEXT) 

編輯:對於str_get_html,這是第五個參數(感謝yitwail)

str_get_html($str, $lowercase=true, $forceTagsClosed=true, $target_charset = DEFAULT_TARGET_CHARSET, $stripRN=true, $defaultBRText=DEFAULT_BR_TEXT, $defaultSpanText=DEFAULT_SPAN_TEXT) 
-2

另一種選擇應該一個希望保留其他格式,如段落&標題是使用innertext而非plaintext然後用結果執行自己的字符串清理。

我意識到存在性能問題,但確實可以實現更細化的控制。

1

如果你經過這裏想知道你是否可以在DomDocument中做同樣的事情,那麼我可以說你可以! - 但它是一個有點髒:(

我的代碼片段,我想整齊,但保留確切的換行符它含有(\ n)的 這是我做過什麼....

// NOTE: If you're HTML isn't a full HTML document then expect DomDocument to 
// start creating its own DOCTYPE, head and body tags. 


// Convert \n into a pretend tag 
$myContent = preg_replace("/[\n]/","<img src=\"slashN\" />",$myContent); 

// Do your DOM stuff... 
$dom = new DOMDocument; 
$dom->loadHTML($myContent); 
$dom->formatOutput = true; 

$myContent = $dom->saveHTML(); 

// Remove the \n's that DOMDocument put in itself 
$myContent = preg_replace("/[\n]/","",$myContent); 

// Put my own \n's back 
$myContent = preg_replace("/<img src=\"slashN\" \/>/i","\n",$myContent); 

重要的是要注意,我知道,毫無疑問,我的輸入僅包含\ n。如果需要考慮\ r \ n或\ t,您可能需要自己的變體,例如slash.T或斜槓。RN等