使用 PHP 收集指定 URL 处的图像并将其存储到数据库中

问题描述 投票:0回答:1

一般来说,我希望输入一个 URL,然后将该 URL 处的图像导入到数据库中。

这是一些让我很满意的代码,但欢迎其他替代方案。

如果我尝试将 $image 作为 BLOB 存储到数据库中,则会出现错误。

<?php



class wSpider
{
    var $ch; /// going to used to hold our cURL instance
    var $html; /// used to hold resultant html data
    var $binary; /// used for binary transfers
    var $url; /// used to hold the url to be downloaded

    function wSpider()
    {
        $this->html = "http:/";
        $this->binary = 0;
        $this->url = "";
    }


    function fetchPage($url)
    {
        $this->url = $url;
        if (isset($this->url)) {
            $this->ch = curl_init(); /// open a cURL instance
            curl_setopt ($this->ch, CURLOPT_RETURNTRANSFER, 1); // tell cURL to return the data
            curl_setopt ($this->ch, CURLOPT_URL, $this->url); /// set the URL to download
            curl_setopt($this->ch, CURLOPT_FOLLOWLOCATION, true); /// Follow any redirects
            curl_setopt($this->ch, CURLOPT_BINARYTRANSFER, $this->binary); /// tells cURL if the data is binary data or not
            $this->html = curl_exec($this->ch); // pulls the webpage from the internet
            curl_close ($this->ch); /// closes the connection
        }
    }
}

$mySpider = new wSpider(); //// creates a new instance of the wSpider
$mySpider->binary = 1; /// turns on the binary transfer mode
$image = $mySpider->fetchPage("http://static.php.net/www.php.net/images/php.gif");

?>
php image web-scraping curl
1个回答
5
投票

你不需要所有这些东西。

你可以这样做:

$image = file_get_contents($url);

然后

pdo::prepare("INSERT INTO img (?, ?)");

© www.soinside.com 2019 - 2024. All rights reserved.