我正在尝试使用PHP编辑DOM文档树。但是,我被卡住了。加载HTML后,我想删除每个元素,除了我指定的少数元素。 (例如<p>
和<b>
)我该怎么做?它甚至可能吗?
以下是我目前的代码:
<?php
$url = 'http://en.wikipedia.org/w/index.php?title=Elephant&action=render';
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13');
$html = '<html>' . curl_exec($curl) . '</html>';
echo $html;
$document = new DOMDocument;
$document->loadHTML($html);
$allowed_elements = array(
'a',
'b',
'i',
'p',
);
$parent = $document->getElementsByTagName('html')->item(0);
foreach ($parent->getElementsByTagName('*') as $element)
{
$node = strtolower((string)$element->nodeName);
if (!in_array($node, $allowed_elements))
{
$element->parentNode->removeChild($element);
}
}
echo $document->saveHTML();
curl_close($curl);
?>
我的修修工告诉我,可以循环遍历DOM树,所以我想我可以循环遍历它。但是,我的代码仍然无效!我试图最终获得明文维基百科的文章 - 如果有人知道我不必自己编写的替代工具,那将是一个可接受的答案。
谢谢! :)
答案 0 :(得分:3)
试试这个:
<?php
$url = 'http://en.wikipedia.org/w/index.php?title=Elephant&action=render';
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13');
$html = '<html>' . curl_exec($curl) . '</html>';
curl_close($curl);
$document = new DOMDocument('1.0');
$document->loadHTML($html);
$allowed_elements = array('a','b','i','p');
$elems = array();
$parent = $document->getElementsByTagName('html')->item(0);
foreach ($parent->getElementsByTagName('*') as $element)
{
$node = (string)$element->nodeName;
if(strtolower($node) == 'body'){
continue;
}
$elems[] = $node;
}
$elems = array_values( array_unique( $elems ) );
$elems = array_diff( $elems, $allowed_elements );
$elems = array_values( array_unique( $elems ) );
sort($elems);
foreach( $elems as $elem ) {
$parent1 = $parent->getElementsByTagName($elem);
$length = $parent->getElementsByTagName($elem)->length;
for($i=0;$i<$length;$i++) {
$el = $parent1->item(0); // 0 is the index because after each `removeChild`, the next element shifts 1 position back.
if( $el ) {
$el->parentNode->removeChild($el);
}
}
}
echo $document->saveHTML();
?>
$ elementsToKeep - 包含不要删除的项目列表的数组。
希望这有帮助。