簡體   English   中英

如何使用php DomXpath解析html,修改並保存

[英]How to parse html with php DomXpath, modify and save

谷歌搜索后找不到與我的問題有關的任何內容。 問題是:我解析頁面,找到一個表[有四個表]。

當我找到時,我想向表中添加一個/一些行/行。 但是我不知道該怎么做。 一些類似的問題與解析xml和查看內容有關。

在代碼中,我有這樣的東西:

$dom = new DOMDocument();
$dom->loadHTML($output->getHTML());
$xpath = new DOMXPath($dom);
$tableProp = $xpath->query('//*[@class="smwb-factbox"][2]');
....
$dom->asHTML();

解決方案很簡單:使用諸如createElement,setAttribute和appendChild之類的方法集可以解決我的問題,示例如下:

$dom = new DOMDocument();
$dom->loadHTML(mb_convert_encoding($output->getHTML(), 'HTML-ENTITIES', 'utf-8'));
$xpath = new DOMXPath($dom);
$tableProp = $xpath->query('//*[@class="smwb-factbox"][2]');
...
$th_el = $dom->createElement('th', $th_outer_inner_span_a_el);
...
$td_el = $dom->createElement('td', '');
$td_el->appendChild($td_el_outer_span);
$tr_el = $dom->createElement('tr', '');
$tr_el->setAttribute('class', 'smwb-propvalue');
$tr_el->appendChild($th_el);
$tr_el->appendChild($td_el);
$tableProp->item(0)->appendChild($tr_el);
$dom->saveHTML();
...

這個想法很簡單。 我在mediawiki中有表格,找到它,保存后創建新行並插入它。 就這樣。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM