简体   繁体   中英

How to download data from a csv feed URL with symfony 4?

With Symfony 4, I need to download the data from a remote URL. Can I use Symfony 4 or do I need to use JQuery or Python or ...? Do I parse the content of the URL or can I download the csv file from the URL?

I'm a newbie, so please talk to me as if I were a dummy.

I'm developping a web application in Symfony 4 that is supposed to download the data (via symfony command and CRON task) from partner stores thanks to a URL they provide on their own web application, eg this one :

 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

I have seen this thread : how to download a file from a url with javascript? The first answer looks interesting but as I said, I'm a newb and I have no idea how to implement the script in my command. And I have seen other threads for Ruby or Angular: How do I download a file with Angular2 How to display and import data from a feed url? but it does't help me much...

edit: I tried to pass the url to fopen but it returns HTTP/1.1 403 Forbidden: Access is denied.

update : Here is my code so far (not much, I'll admit) with everything I've tried and the results :

    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');
        }

And here is the code of my converter :

 /**
     * 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;
    }

I guess I miss a step. I can't read a file directly from the URL so I must retrieve the file before trying to read it. How can I do that?

To download the data from a feed URL, in my case, a csv file, You have to send a request to the URL. Symfony is not designed to send requests to external URL so you have to use cURL or Goutte or Guzzle . I chose Guzzle. Here is how I used it:

 $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 is the url I must send the request to.

Don't forget to import Guzzle between the namespace and the class : use GuzzleHttp\\Client; .

With this code, you get the whole body of the page, ie what you get contains html tags such as this :

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

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

Once you get the data, you must write it in a file so you create a

$filePath = 'public/my_data/myFile';

and you create/open the file :

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

Then you write in the file :

fwrite($fp, $body);

And don't forget to close the file to avoid memory leak :

fclose($fp);

Finally, you'll just have to convert the file at your convenience. Just remember that mode 'x' in fopen() creates a file and returns an error if a file with same name already exists.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM