PHP uses the generator yield keyword to process more than a CSV file and re-export

Source: Internet
Author: User

A few days ago a task is to decrypt a field in Excel, originally is a very simple thing, but the problem is to use Phpexcel has been unable to load Excel, regardless of the running time set to unlimited, memory also increased to 2048M, still not, finally all kinds of asked Niang, The last time I saw the generator yield, it was just a chance to test.


classqushu{ Public functionGETDG () {Set_time_limit(0); $file= Request ()->get (' file '); $path= ' d:/path/'.$file.‘. csv; $key= ' ******** '; $header= [' Order ', ' name ', ' phone ', ' address ', ' ID number ', ' Institution ', ' Social code ', ' tax ', ' test ', ' Test call ', ' know ', ' Item name ']; $output=$this->csvset ("Export table name",$header); $data=$this->getcsv ($path); $i= 0; foreach($data  as $k=$v)        {            if(!$v) Break; $idcard=Iconv(' GBK ', ' Utf-8//translit//ignore ',$v[4]); //determine whether to work with fields based on criteria            if(!Empty($idcard) &&strlen($idcard) >18){                //process The field of code ....                $v[4] = "; }            //Output CSV contentFputcsv ($output,array_values($v)); $i++; }        //Close file handle        fclose($output) or die("Can ' t close php://output"); Exit; }    /** * Get CSV content using yield*/     Public functionGetcsv ($fname)    {        $handle=fopen("$fname", ' RB ');  while(feof($handle)===false) {            #code ...YieldFgetcsv($handle); }        fclose($handle); }    /** Set CSV*/     Public functionCsvset ($name,$head)    {        Try {            //set up memory consumption            Set_time_limit(0); Ini_set(' Memory_limit ', ' 512M '); //open a file handle for the Fputcsv () function            $output=fopen(' Php://output ', ' W ') or die("Can ' t open php://output"); //tell the browser that this is a CSV file            Header("Content-type:application/csv"); Header("Content-disposition:attachment; Filename=$name. csv "); Header(' Cache-control:must-revalidate,post-check=0,pre-check=0 '); Header(' expires:0 '); Header(' Pragma:public '); //filename transcoding            $name=Iconv(' Utf-8 ', ' GBK ',$name); //Output Table Header            foreach($head  as $i=$v) {                //CSV Excel support GBK encoding, be sure to convert otherwise garbled                $head[$i] =Iconv(' Utf-8 ', ' GBK ',$v); } fputcsv ($output,$head); return $output; }Catch(Exception $e){        }    }}  

As can be seen from the above, just through the yield identification process a generator, called the Getcsv method to obtain an iterator, then by looping this iterator, the logical operation can be.


    1. Generators, providing an easier way to implement iterations, with significantly lower performance overhead and complexity
    2. The generator function looks like a normal function, except that the normal function returns a value, and a generator can yield generate many of the values it needs, and each time the generated return value just pauses the current execution state, and the next time the generator function is called, PHP resumes execution from the last paused state.
    3. Using the generator to process large files, because yield does not take all the data at once, instead generates an iterator that loops, and internally pairs the resulting value with a contiguous integer index, like a non-associative array. Save memory resources by taking a specified piece of data from the cursor per loop

PHP uses the generator yield keyword to process more than a CSV file and re-export

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.