11

DOMDocumentクラスを使用して HTML 要素を削除する方法はありますか?

4

2 に答える 2

22

DOMNode::removeChildDave Morgan の回答に加えて、子のリストから子を削除するために使用できます。

タグ名による子の削除

//The following example will delete the table element of an HTML content.

$dom = new DOMDocument();

//avoid the whitespace after removing the node
$dom->preserveWhiteSpace = false;

//parse html dom elements
$dom->loadHTML($html_contents);

//get the table from dom
if($table = $dom->getElementsByTagName('table')->item(0)) {

   //remove the node by telling the parent node to remove the child
   $table->parentNode->removeChild($table);

   //save the new document
   echo $dom->saveHTML();

}

クラス名による子の削除

//same beginning
$dom = new DOMDocument();
$dom->preserveWhiteSpace = false;
$dom->loadHTML($html_contents);

//use DomXPath to find the table element with your class name
$xpath = new DomXPath($dom);
$classname='MyTableName';
$xpath_results = $xpath->query("//table[contains(@class, '$classname')]");

//get the first table from XPath results
if($table = $xpath_results->item(0)){

    //remove the node the same way
    $table ->parentNode->removeChild($table);

    echo $dom->saveHTML();
}   

資力

http://us2.php.net/manual/en/domnode.removechild.php

DOMDocumentで要素を削除するには?

DOMXPath::query() メソッドから完全な HTML を取得するには?

于 2014-12-08T08:35:50.803 に答える
13

http://us2.php.net/manual/en/domnode.removechild.php

DomDocumentはDomNodeです。removechildを呼び出すだけで、問題はありません。

編集:あなたが現在作業しているページについて話している可能性があることに気づきました。DomDocumentが機能するかどうかわからない。その時点でjavascriptを使用することを検討することをお勧めします(すでにクライアントに提供されている場合)

于 2009-07-23T13:12:54.197 に答える