0

我正在尝试使用 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 树,所以我假设我可以循环遍历它。但是,我的代码仍然无法正常工作!我试图最终获得明文维基百科文章——如果有人知道我不必自己编写的替代工具,那将是一个可以接受的答案。

谢谢!!:)

4

1 回答 1

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 - 该数组包含不被删除的项目列表。

希望这可以帮助。

于 2012-05-24T08:10:26.367 回答