正則規則寫好後,頁面一旦有改變就要重新修改正則。
先提取頁面的 DOM,有沒有比較好的辦法?
回複內容:
正則規則寫好後,頁面一旦有改變就要重新修改正則。
先提取頁面的 DOM,有沒有比較好的辦法?
我想你需要的是 php 的 DOM 模組 ... 預設有安裝不用擔心 ...
因為不知道你的實際應用情境是什麼 ... 給你寫個簡單的例子吧 ...
loadHTML( <<Sunyanzi's Test Hello World
Hey WelcomeHTML_SECTION);/* now we should try to get something ... */$h1Elements = $doc->getElementsByTagName( 'h1' );/* this line prints "Hello World" ... */foreach( $h1Elements as $h1Node ) echo $h1Node->nodeValue, PHP_EOL;/* and this line prints "http://segmentfault.com/" ... */echo $doc->getElementById( 'onlylink' )->getAttribute( 'href' ), PHP_EOL;/* now i will introduce something advanced ... using XPath ... */$xpath = new DOMXPath( $doc );/* also prints "http://segmentfault.com/" ... locate via h1 ... */echo $xpath->evaluate( 'string(//h1[text()="Hello World"]/following-sibling::a/@href)' ), PHP_EOL;
基本上 ... 等到你熟練掌握 XPath 之後 ... 你會發現 DOM 比正則要靈活得多 ...
php 處理 XML 的能力遠遠超乎你的想象 ... 有空讀讀手冊不是壞事恩 ...
你說的很對。我現在就用xpath。。。