Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/lua/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP-读取三行远程html_Php_File Get Contents_Trim - Fatal编程技术网

PHP-读取三行远程html

PHP-读取三行远程html,php,file-get-contents,trim,Php,File Get Contents,Trim,我需要使用PHP读取远程页面的三行。我正在使用Jose Vega的代码阅读标题: <?php function get_title($url){ $str = file_get_contents($url); if(strlen($str)>0){ $str = trim(preg_replace('/\s+/', ' ', $str)); // supports line breaks inside <title> preg_match(

我需要使用PHP读取远程页面的三行。我正在使用Jose Vega的代码阅读标题:

<?php

function get_title($url){
  $str = file_get_contents($url);
  if(strlen($str)>0){
    $str = trim(preg_replace('/\s+/', ' ', $str)); // supports line breaks    inside <title>
    preg_match("/\<title\>(.*)\<\/title\>/i",$str,$title); // ignore case
    return $title[1];
  }
}
//Example:
echo get_title("http://www.washingtontimes.com/");

?>

根据你的问题,我猜你想阅读元数据。我现在建议的部分代码取自
。它适用于此SO页面,因此也适用于您的页面。当然,您需要对其进行一些调整以完成任务

function getUrlData($url, $raw=false) // $raw - enable for raw display
{
    $result = false;

    $contents = getUrlContents($url);

    if (isset($contents) && is_string($contents))
    {
        $title = null;
        $metaTags = null;
        $metaProperties = null;

        preg_match('/<title>([^>]*)<\/title>/si', $contents, $match );

        if (isset($match) && is_array($match) && count($match) > 0)
        {
            $title = strip_tags($match[1]);
        }

        preg_match_all('/<[\s]*meta[\s]*(name|property)="?' . '([^>"]*)"?[\s]*' . 'content="?([^>"]*)"?[\s]*[\/]?[\s]*>/si', $contents, $match);

        if (isset($match) && is_array($match) && count($match) == 4)
        {
            $originals = $match[0];
            $names = $match[2];
            $values = $match[3];

            if (count($originals) == count($names) && count($names) == count($values))
            {
                $metaTags = array();
                $metaProperties = $metaTags;
                if ($raw) {
                    if (version_compare(PHP_VERSION, '5.4.0') == -1)
                         $flags = ENT_COMPAT;
                    else
                         $flags = ENT_COMPAT | ENT_HTML401;
                }

                for ($i=0, $limiti=count($names); $i < $limiti; $i++)
                {
                    if ($match[1][$i] == 'name')
                         $meta_type = 'metaTags';
                    else
                         $meta_type = 'metaProperties';
                    if ($raw)
                        ${$meta_type}[$names[$i]] = array (
                            'html' => htmlentities($originals[$i], $flags, 'UTF-8'),
                            'value' => $values[$i]
                        );
                    else
                        ${$meta_type}[$names[$i]] = array (
                            'html' => $originals[$i],
                            'value' => $values[$i]
                        );
                }
            }
        }

        $result = array (
            'title' => $title,
            'metaTags' => $metaTags,
            'metaProperties' => $metaProperties,
        );
    }

    return $result;
}

function getUrlContents($url, $maximumRedirections = null, $currentRedirection = 0)
{
    $result = false;

    $contents = @file_get_contents($url);

    // Check if we need to go somewhere else

    if (isset($contents) && is_string($contents))
    {
        preg_match_all('/<[\s]*meta[\s]*http-equiv="?REFRESH"?' . '[\s]*content="?[0-9]*;[\s]*URL[\s]*=[\s]*([^>"]*)"?' . '[\s]*[\/]?[\s]*>/si', $contents, $match);

        if (isset($match) && is_array($match) && count($match) == 2 && count($match[1]) == 1)
        {
            if (!isset($maximumRedirections) || $currentRedirection < $maximumRedirections)
            {
                return getUrlContents($match[1][0], $maximumRedirections, ++$currentRedirection);
            }

            $result = false;
        }
        else
        {
            $result = $contents;
        }
    }

    return $contents;
}

$result = getUrlData('https://stackoverflow.com/questions/51939042/php-read-three-lines-of-remote-html', true);
然后实际使用它来达到你的目的:

如何使用此脚本高效解析数十个站点?这个 所有地点都在上升。index.php?id=103 index.php?id=104 index.php?id=105

您需要:

  • -首先创建一个包含URL的
    数组

    <!DOCTYPE html>
                <html>
                <head>
                </head>
                <body>
    
                <h2>HTML Table</h2>
    
                <table>
                        <tr>
                        <th >Id</th>
                        <th >Title</th>
                        <th >start_date</th>
                        <th>end_date</th>
                        </tr>
            <?php
    $urls=array(103=>'index.php?id=103',104=> 'index.php?id=104', 105=>'index.php?id=105');
    
  • -每次迭代使用函数
    getUrlData()
    ,如图所示:

        $result=getUrlData($url, true);
    
  • -然后,使用以下方法检索所需信息:

    ?><tr>
      <td><?php echo $id; ?></td>
      <td><?php echo $result['title']; ?></td>
      <td><?php echo $result['metaProperties']['start_date']['value']; ?></td>
      <td><?php echo $result['metaProperties']['end_date']['value']; ?></td>
    </tr>
    
    ?>
    
    创建每一行和每一行。 在该过程结束时,您将得到预期的表:

    Endforeach;?>
                </table></body>
                </html>
    
    Endforeach;?>
    

  • 好的,您可以使用DomDocument类解决您的问题

    $doc = new \DomDocument();
    $title = $start = $end = '';
    
    if ($doc->loadHTMLFile($url)) {
    
        // Get the title
        $titles = $dom->getElementsByTagName('title');
        if ($titles->length > 0) {
            $title = $titles->item(0)->nodeValue;
        }
    
        // get meta elements
        $xpath = new \DOMXPath($doc);
        $ends = $xpath->query('//meta[@property="end_date"]');
        $if ($ends->length > 0) {
            $end = $ends->item(0)->getAttribute('content');
        }
    
        $starts = $xpath->query('//meta[@property="start_date"]');
        if ($starts->length > 0) {
            $start = $starts->item(0)->getAttribute('content');
        }
    
        var_dump($title, $start, $end);
    }
    
    使用
    DomDocument
    类的
    getElementsByTagName
    方法,可以在给定url的整个html中找到title元素。使用
    DOMXPath
    类,您可以检索所需的特定元数据。在html字符串中查找特定信息不需要太多代码


    上面显示的代码未经测试。

    这似乎是非常基本的PHP。在这个网站上,你需要展示你已经尝试过的代码,并请求帮助。这不是一个免费的咨询网站:-)。话虽如此,您能否提供几个示例站点,并感谢@bcperth。正如你所看到的,我发布了我正在尝试的代码,但没走多远,所以我向专业人士寻求帮助。我知道你想避免人们来这里要求免费编码。我还远远不是一个php程序员。这是一个非常彻底和深入的答案,但遗憾的是,我没有得到它来正确显示结果。而endforeach根本没有解析。它显示数组中第一个项目的ID和标题,但不显示其他项目。没有开始或结束日期。这是现场代码。您的代码中有许多错误。这就是它不起作用的原因。它对我起作用您在第96行得到了一个错误:而不是:
    foreach($id=>url)您必须编写:
    foreach($id=>$url):
    您还必须编写
    您还需要在步骤4更改代码:而不是
    $result['metaTags']
    使用
    $result['metaProperties']
    它可以很好地处理这些更改。非常感谢!!!在玩get_meta_标签时,我永远也不会想到这一点。这是一种更简单的编码。我能像index.php那样简单地调用它吗?url=www.sample.com?或者我可以在循环中使用loadHTMLFile($url)使用一个数组,比如Elemental的answer?您可以在循环中执行这段代码,也可以使用GET参数。我更喜欢GET参数解决方案,通过CURL调用它为
    index.php?url=www.sample.com
    ,并以JSON字符串或类似的形式返回所需的数据。在本例中,运行时和内存使用量小于运行循环,因为您会反复使用每个新的url GET参数启动脚本。无论如何你可以用两种方法。你自己决定哪一个。
        $result=getUrlData($url, true);
    
    ?><tr>
      <td><?php echo $id; ?></td>
      <td><?php echo $result['title']; ?></td>
      <td><?php echo $result['metaProperties']['start_date']['value']; ?></td>
      <td><?php echo $result['metaProperties']['end_date']['value']; ?></td>
    </tr>
    
    Endforeach;?>
                </table></body>
                </html>
    
    $doc = new \DomDocument();
    $title = $start = $end = '';
    
    if ($doc->loadHTMLFile($url)) {
    
        // Get the title
        $titles = $dom->getElementsByTagName('title');
        if ($titles->length > 0) {
            $title = $titles->item(0)->nodeValue;
        }
    
        // get meta elements
        $xpath = new \DOMXPath($doc);
        $ends = $xpath->query('//meta[@property="end_date"]');
        $if ($ends->length > 0) {
            $end = $ends->item(0)->getAttribute('content');
        }
    
        $starts = $xpath->query('//meta[@property="start_date"]');
        if ($starts->length > 0) {
            $start = $starts->item(0)->getAttribute('content');
        }
    
        var_dump($title, $start, $end);
    }