php - 在 PHP 中使用 URL 获取元素的特定内容 block

标签 php file-get-contents

<分区>

Possible Duplicate:
How to parse and process HTML with PHP?

我知道 file_get_contents(url) 方法,但我想要的是也许首先使用 file_get_contents(url) 来提取页面的内容,然后是否有一些方法/函数可以从页面中提取或获取特定的内容 block 您使用 file_get_contents(url) 获取的内容?这是一个示例:

所以代码会是这样的:

$pageContent = file_get_contents('http://www.pullcontentshere.com/');

这将是 $pageContent 的输出

<html> <body>
    <div id="myContent">
        <ul>    
            <li></li>
            <li></li>
            <li></li>
        </ul>
    </div> 
</body> </html>

也许您有什么建议或想到如何具体提取 <div id="myContent">以及它的所有 child ?

所以它会是这样的:

$content = function_here($pageContent);

所以输出应该是这样的:

        <div id="myContent">
            <ul>    
                <li></li>
                <li></li>
                <li></li>
            </ul>
        </div> 

非常感谢您的回答!

最佳答案

另一种方法是使用正则表达式。

<?php

$string = '<html> <body> 
    <div id="myContent"> 
        <ul>     
            <li></li> 
            <li></li> 
            <li></li> 
        </ul> 
    </div>  
</body> </html>';

if ( preg_match ( '/<div id="myContent"(.*?)<\/div>/s', $string, $matches ) )
{
    foreach ( $matches as $key => $match )
    {
        echo $key . ' => ' . htmlentities ( $match ) . '<br /><br />';
    }
}
else
{
    echo 'No match';
}

?>

实例:http://codepad.viper-7.com/WSoWCh

关于php - 在 PHP 中使用 URL 获取元素的特定内容 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10768275/

相关文章:

PHP file_get_contents() 返回 "failed to open stream: HTTP request failed!"

javascript - PHP 脚本未在服务器 shell 上显示正确的数据

php - file_get_contents 通过 tor

php - 用PHP压缩文件目录

php - 从mysql获取日期和时间输出到html表中

php - 不使用服务器端验证的后果?

php - session 数据的 file_get_contents(或 curl 或 fopen)问题

php - file_get_contents() 不会超时/返回 HTTPS url 错误

javascript - 如何获取OPTION的TEXT值

php - 如何使用 ini_set 设置 smtp 用户名和密码