【问题标题】:Get the biggest image from url with php使用php从url获取最大的图像
【发布时间】:2013-05-25 13:31:27
【问题描述】:

各位,我的代码是:

<?php
include('simple_html_dom.php');
$url = "http://www.google.si";
$html = file_get_html($url);
$largest_file_size=0;
$largest_file_url='';

// Go through all images of that page
foreach($html->find('img') as $element){
    // Helper function to make absolute URLs from relative
    $img_url=$this->InternetCombineUrl($url,$element->src);
    // Try to get image file size info from header:
    $header=array_change_key_case(get_headers($img_url, 1));
    // Only continue if "200 OK" directly or after first redirect:
    if($header[0]=='HTTP/1.1 200 OK' || @$header[1]=='HTTP/1.1 200 OK'){
        if(!empty($header['content-length'])){
            // If we were redirected, the second entry is the one.
            // See http://us3.php.net/manual/en/function.filesize.php#84130
            if(!empty($header['content-length'][1])){
                $header['content-length']=$header['content-length'][1];
            }
            if($header['content-length']>$largest_file_size){
            $largest_file_size=$header['content-length'];
            $largest_file_url=$img_url;
            }
        }else{ 
            // If no content-length-header is sent, we need to download the image to check the size
            $tmp_filename=sha1($img_url);
            $content = file_get_contents($img_url);
            $handle = fopen(TMP.$tmp_filename, "w");
            fwrite($handle, $content);
            fclose($handle);
            $filesize=filesize(TMP.$tmp_filename);
            if($filesize>$largest_file_size){
            $largest_file_size=$filesize;
            $largest_file_url=$img_url;
            unlink(TMP.$tmp_filename);
            }
        }
    }
}
?>

我遇到了以下问题: 致命错误:在第 11 行的 C:\xampp\htdocs\sandbox\agregat\test.php 的对象上下文中使用 $this

有什么帮助吗?

【问题讨论】:

    标签: php image url dom fatal-error


    【解决方案1】:

    问题出在这一行

     $img_url=$this->InternetCombineUrl($url,$element->src);
    

    您使用 $this 对不存在的对象的引用。 $this 只能在类内部使用,并且引用当前对象。您可以用类包装代码,还需要提供 InternetCombineUrl 方法。另一种解决方案是删除 $this-> 但您需要创建函数 InternetCombineUrl 并且它也可以工作。

    【讨论】:

    【解决方案2】:

    错误信息说明了一切。

    来自the manual

    当从对象上下文中调用方法时,伪变量 $this 可用。 $this 是对调用对象的引用(通常是方法所属的对象,但也可能是另一个对象,如果该方法是从辅助对象的上下文中静态调用的)。

    你不能在课堂之外使用它。看起来该代码是从一个类中剪切和粘贴的,如果不先修改就无法工作。

    【讨论】:

    • 所以如果我理解正确的话,foreach 可以进入函数,它被包装在一个类中,然后我可以从类外调用这个函数? $this 应该可以工作,因为它将在对象上下文中引用?
    • 将 InternetCombineUrl() 函数复制到你得到的类之外,并将其用作独立函数,没有 $this(因为你不在一个类中)
    猜你喜欢
    • 2013-07-15
    • 2020-03-14
    • 1970-01-01
    • 2017-09-21
    • 2015-12-17
    • 2021-11-19
    • 2012-09-16
    • 2016-11-15
    • 2017-02-02
    相关资源
    最近更新 更多