download - 如何使用 symfony 4 从 csv feed URL 下载数据?

标签 download symfony4

使用 Symfony 4,我需要从远程 URL 下载数据。我可以使用 Symfony 4 还是需要使用 JQuery 或 Python 还是......?我是否可以解析 URL 的内容,或者可以从 URL 下载 csv 文件吗?

我是新手,所以请像我是傻瓜一样跟我说话。

我正在 Symfony 4 中开发一个 Web 应用程序,该应用程序应该从合作伙伴商店下载数据(通过 symfony 命令和 CRON 任务),这要归功于他们在自己的 Web 应用程序上提供的 URL,例如这个:

 Wine Title Vintage Country Region  Sub region  Appellation Color   Bottle Size Price   URL FORMAT
The Last Drop 1971 Scotch       Scotland                    750ML   3999.99 HTTP://buckhead.towerwinespirits.com/sku63174.html  1x750ML
Petrus Pomerol  2015    France  Bordeaux                750ML   3799.99 HTTP://buckhead.towerwinespirits.com/sku40582.html  1x750ML
Remy Martin Louis XIII Cognac       France  Cognac              750ML   3499.99 HTTP://buckhead.towerwinespirits.com/sku15758.html  1x750ML
Hennessy Paradis Imperial Cognac        France  Cognac              750ML   3299.99 HTTP://buckhead.towerwinespirits.com/sku51487.html  1x750ML

我看过这个帖子: how to download a file from a url with javascript? 第一个答案看起来很有趣,但正如我所说,我是新手,我不知道如何在我的命令中实现脚本。 我还看到了 Ruby 或 Angular 的其他线程: How do I download a file with Angular2 How to display and import data from a feed url? 但这对我帮助不大...

编辑:我尝试将 url 传递给 fopen,但它返回 HTTP/1.1 403 Forbidden:访问被拒绝。

更新:这是到目前为止我的代码(不多,我承认)以及我尝试过的所有内容和结果:

    class UpdateArticlesCommand extends Command
    {
        protected static $defaultName = 'app:update-articles';
        protected $em = null;

        protected function configure()
        {
            $this
                ->setDescription('Updates the articles of the stores having set a feed URL')
                ->setHelp('This command allows you to update the articles of the stores which have submitted a feed URL');
        }

        /**
         * UpdateArticlesCommand constructor.
         * @param EntityManagerInterface $em
         * @param string|null $name
         */
        public function __construct(EntityManagerInterface $em, ?string $name = null)
        {
            $this->em = $em;
            parent::__construct($name);
        }


        protected function execute(InputInterface $input, OutputInterface $output)
        {
            $io = new SymfonyStyle($input, $output);
            $io->title('Attempting to import the feeds...');
            $converter = new ConverterToArray();
$io->writeln([$store->getFeedUrl()]);

            $url = $store->getFeedUrl();
//            dd($url);     //OK
            $feedColumnsMatch = $store->getFeedColumnsMatch();
//            dd($feedColumnsMatch);    //OK


            $fileName = $store->getName().'Feed.txt';
            $filePath = $fileUploader->getTargetDirectory() . "/" . $fileName;

                                                               /* //sends a http request and save the given file
                                                                set_time_limit(0);
                                                                $fp = fopen($filePath, 'x+');

                                                                $ch = curl_init($url);
                                                                curl_setopt($ch, CURLOPT_TIMEOUT, 50);

                                                                // give curl the file pointer so that it can write to it
                                                                curl_setopt($ch, CURLOPT_FILE, $fp);
                                                                curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

                                                                $data = curl_exec($ch);//get curl response
                                                                curl_close($ch);

                                                                dd($data);          //return false*/



                                                                /*dd($this->curl_get_file_contents($url));        //returns false*/


            $client = new Client();
            $response = $client->request('GET', $url);

            echo $response->getStatusCode(); # 200
            echo $response->getHeaderLine('content-type'); // 'application/json; charset=utf8'
            echo $response->getBody(); // '{"id": 1420053, "name": "guzzle", ...}'

            $articlesArray = $converter->convert("https://myURL.com", $feedColumnsMatch);
            }
            $io->success('Successful upload');
        }

这是我的转换器的代码:

 /**
     * is used to convert a csv file into an array of data
     * @param $filePath
     * @param FeedColumnsMatch $feedColumnsMatch
     * @return array|string
     */
    public function convert($filePath, $feedColumnsMatch)
    {

//        if(!file_exists($filePath) ) {
//            return "existe pas";
//        }
//        if(!is_readable($filePath)) {
//            return "pas lisible";
//        }

        //this array will contain the elements from the file
        $articles = [];
        $headerRecord = [];

        if($feedColumnsMatch->getFeedFormat()==="tsv" | $feedColumnsMatch->getFeedFormat()==="csv"){
            if($feedColumnsMatch->getFeedFormat()==="csv"){
                $delimiter = $feedColumnsMatch->getDelimiter();
            }else{
                $delimiter = "\t";
            }

            //if we can open the file on mode "read"
            if (($handle = fopen($filePath, 'r')) !== FALSE) {
                //represents the line we are reading
                $rowCounter = 0;

                //as long as there are lines
                while (($rowData = fgetcsv($handle, 1000, $delimiter)) !== FALSE) {
                    //At first line are written the keys so we record them in $headerRecord
                    if(0 === $rowCounter){
                        $headerRecord = $rowData;
                    }else{      //for every other lines...
                        foreach ($rowData as $key => $value){       //in each line, for each value
                            // we set $value to the cell ($key) having the same horizontal position than $value
                            // but where vertical position = 0 (headerRecord[]
                            $articles[$rowCounter][$headerRecord[$key]]= $value;
                        }
                    }
                    $rowCounter++;
                }
                fclose($handle);
            }
        }
        return $articles;
    }

我想我错过了一步。我无法直接从 URL 读取文件,因此我必须在尝试读取文件之前检索该文件。我怎样才能做到这一点?

最佳答案

要从 Feed URL 下载数据(在我的例子中是 csv 文件), 您必须向该 URL 发送请求。 Symfony 并非设计用于向外部 URL 发送请求,因此您必须使用 cURL 或 GoutteGuzzle 。 我选择了咕咕。以下是我的使用方法:

 $client = new Client();
            $response = $client->request('GET', $url);

            echo "Status Code = ".$response->getStatusCode()."\n"; # 200
            echo 'Content Type = '.$response->getHeaderLine('content-type')."\n"; 

            $body = $response->getBody();

$url 是我必须将请求发送到的 url。

不要忘记在命名空间和类之间导入 Guzzle : 使用 GuzzleHttp\Client; .

使用此代码,您可以获得页面的整个主体,即您获得的内容包含如下所示的 html 标签:

<!DOCTYPE html>
<html lang="en">
    <body>
        <pre>
            Wine Directory List
            <BR>
//here is the content of the csv file

        </pre>
    </body>
</html>

获取数据后,必须将其写入文件中,以便创建一个

$filePath = 'public/my_data/myFile';

然后您创建/打开文件:

$fp = fopen($filePath, 'x');

然后你在文件中写入:

fwrite($fp, $body);

并且不要忘记关闭文件以避免内存泄漏:

fclose($fp);

最后,您只需在方便时转换文件即可。请记住,fopen() 中的模式“x”创建一个文件,如果同名文件已存在,则返回错误。

关于download - 如何使用 symfony 4 从 csv feed URL 下载数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56667046/

相关文章:

Android内存不足预防

Android:从 URL 下载返回的 Zip 文件

docker - Symfony 4 生成 SQLSTATE[HY000] [2002] 使用 Docker 容器拒绝连接

php - 替换/装饰 `translation.reader`

php - 使用开发依赖项在 Heroku 上部署时,尝试从命名空间 "WebProfilerBundle"加载类 "Symfony\Bundle\WebProfilerBundle"

android - 如何在 Android 中以编程方式从网上下载文件?

angularjs - 使用 angularJs 资源下载 XML 文件

serialization - Symfony 4序列化没有关系的实体

jwt - API 平台 JWT : No route found for "GET/api/login"

python - 下载并安装 scapy for windows for python 3.5?