-1

How to delete all data in div by id after using file_get_contents php [Using PHP]?

I want to delete all data inside div id="one"

This is coding on https://www.example.com

<div id="main">
    <div id="inner">
        <div id="one">
            <div>
                HELLO
            </div>
            HELLO
        </div>
        <div id="two">
            TEST
        </div>
    </div>
</div>

.

<?PHP
$home_page = file_get_contents("https://www.example.com");
echo $home_page;
?>

When finished i want to get data like this

<div id="main">
    <div id="inner">
        <div id="two">
            TEST
        </div>
    </div>
</div>

How can i do ?

Best regards, mongkon tiya

2 Answers2

0

Edit: Readed you want an plain PHP solution, sry this is a JS solution.

echo '<script type="text/javascript">',
     'var elem = document.getElementById("one"); elem.remove();',
     '</script>'

Just call in php via echo after your file_get_contents a script. I write it in plain js, if its not working and ure using an older browser use:

echo '<script type="text/javascript">',
         'var elem = document.getElementById("one"); elem.parentNode.removeChild(elem);
         '</script>

If you use Jquery u can also just use the function .remove();

Doomenik
  • 868
  • 1
  • 12
  • 29
0

In order to accomplish this sort of DOM manipulation using only PHP you need to use output buffering and DOMDocument

<?php
    ob_start(); /* tell php to buffer the output */
?>

<!-- typical html page - there MUST be a doctype though!-->
<!--
<!doctype html>
<html>
    <head>
        <title>Output buffer test</title>
    </head>
    <body>
        <div id='main'>
            <div id='inner'>
                <div id='one'>
                    <div>
                        Hello World
                    </div>
                    hello
                </div>
                <div id='two'>
                    Goodbye Cruel World
                </div>
            </div>
        </div>
    </body>
</html>
-->

<?php
    echo file_get_contents('http://www.example.com');
?>


<!-- manipulate the DOM  using PHP only -->
<?php
    libxml_use_internal_errors( true );

    /* read the currently stored buffer and load into DOMDocument */
    $buffer=@ob_get_contents();
    $dom=new DOMDocument;
    $dom->loadHTML( $buffer );
    libxml_clear_errors();

    /* Find the DOM element you wish to remove */
    $div=$dom->getElementById('one');
    $div->parentNode->removeChild( $div );

    /* Save the current DOM and flush the buffer */
    $buffer=$dom->saveHTML();
    @ob_end_clean();

    echo $buffer;

    if( @ob_get_level() > 0 ) {
        for( $i=0; $i < ob_get_level(); $i++ ) @ob_flush();
        @ob_end_flush();
    }
    $dom=null;
?>
Professor Abronsius
  • 33,063
  • 5
  • 32
  • 46