简体   繁体   中英

PHP DOMDocument: Delete elements

I' trying to delete class of HTML code. But doesen't work. My problem is that I don't know how to remove a specific <div> . I have only error:

Argument 1 passed to DOMXPath::__construct() must be an instance of DOMDocument, string given in

It's HTML Structure:

 <section id="tresc" > <div class="todelete1"> <strong >text to delete</strong> </div> <b>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</b> <div id="todelete_2" class="todelete2"> <script type="text/javascript"> GR("blabla","center"); </script> </div> <br>Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.<br> <br><i> <a href="http://www.lipsum.com/" class="lipsum">LIPSUM</a> Text</i> <br> <br> //all below to delete <img src="todelete3.jpg"> <br><b>*<a href="http://nothing1.com" title="to delete4">to delete4</a></b> <br><b>*<a href="http://nothing2.com" title="to delete5">to delete5</a></b> <br><b>*<a href="http://nothing3.com" title="to delete6">to delete6</a></b> </section> 

I have the following code:

$ht = file_get_contents('http://localhost:8080/lesson/test17.html');
$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTML($ht);
$divs = $dom->getElementsByTagName('section');
foreach ($divs as $div)
{
    if($div->getAttribute('id') == 'tresc') 
    {
        $before = $dom->saveHTML($div);
        $selector = new DOMXPath($before);
        foreach($selector->query('//div[contains(attribute::class, "todelete1")]') as $e ) 
        {
            $e->parentNode->removeChild($e);
        }
        echo $before->saveHTML($before->documentElement);

    }

}

How can remove to grab the div with class todelete1 , todelete2 and all links bellow </i> ?

I don't need it! Thx for help me.

The main misunderstanding with your code is the DOMXPath init. You render the HTML of <section id="tresc"> into $before variable and then you try to instantiate a DOMXPath passing $before as argument: DOMXPath argument must be a “DOMDocument object” , but you pass a string (the rendered HTML) instead.

To correctly init DOMXPath , you have to pass as argument $dom itself, and you can init it once, just after loading HTML into $dom object. There is no need to create a new DOMXPath for each node.

Side error: the syntax when you — at end of code — try to render HTML of <div> . You use this syntax: renderedHTLM->saveHTML( renderedHTML->documentElement ) instead of correct syntax: DOMDocumentObj->saveHTML( DOMElementContext ) . You have to change this line in $dom->saveHTML( $div )

So, you can change the code in this way:

$ht = file_get_contents( 'http://localhost:8080/lesson/test17.html' );
$dom = new DOMDocument();
libxml_use_internal_errors( true );
$dom->loadHTML( $ht );

$selector = new DOMXPath( $dom );                                   // <----

$divs = $dom->getElementsByTagName('section');

foreach( $divs as $div )
{
    if( $div->getAttribute( 'id' ) == 'tresc' ) 
    {
        foreach($selector->query( '//div[contains(attribute::class, "todelete1")]' ) as $e ) 
        {
            $e->parentNode->removeChild($e);
        }
        echo $dom->saveHTML( $div );                                // <----
    }
}

Side note: if you want delete an element with an id attribute, you can use ->getElementbyId ( id is unique in the HTML page), and shorten your code in this way:

$div = $dom->getElementById( 'tresc' );
$div->parentNode->removeChild( $div );

thx @fusion3k it's work very well. I deleted all <div> but i have last question how delete all a or img selector of code i know is strip_tags but this function leave text for my example

to delete4, to delete5, to delete6

.

$divs = $dom->getElementsByTagName('section');

foreach( $divs as $div )
{
    if( $div->getAttribute( 'id' ) == 'tresc' ) 
    {
        foreach($selector->query( '//div[contains(attribute::class, "todelete1")]' ) as $e ) 
        {
            $e->parentNode->removeChild($e);
        }
        foreach($selector->query( '//div[contains(attribute::class, "todelete2")]' ) as $f ) 
        {
            $f->parentNode->removeChild($f);
        }
        foreach($selector->query( '//a[contains(attribute::href,""]' ) as $g) 
        {
            $g->parentNode->removeChild($g);
        }
        echo $dom->saveHTML( $div );  

thx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM