如何在使用file_get_contents
php [使用PHP]后删除div中的所有数据?
我想删除div id="one"
这是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;
?>
完成后我想获得这样的数据
<div id="main">
<div id="inner">
<div id="two">
TEST
</div>
</div>
</div>
我该怎么办?
祝你好运, mongkon tiya
答案 0 :(得分:0)
编辑:Readed你想要一个简单的PHP解决方案,这是一个JS解决方案。
echo '<script type="text/javascript">',
'var elem = document.getElementById("one"); elem.remove();',
'</script>'
在file_get_contents脚本之后,只需通过echo调用php。我用简单的js写它,如果它不起作用并使用较旧的浏览器使用:
echo '<script type="text/javascript">',
'var elem = document.getElementById("one"); elem.parentNode.removeChild(elem);
'</script>
如果您使用Jquery,您也可以使用函数.remove();
答案 1 :(得分:0)
为了仅使用PHP完成这种DOM操作,您需要使用output buffering
和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;
?>