Using curl as an alternative to fopen file resource for fgetcsv

后端 未结 2 541
南旧
南旧 2021-02-09 08:30

Is it possible to make curl, access a url and the result as a file resource? like how fopen does it.

My goals:

  1. Parse a CSV file
  2. Pass it to fgetcsv
2条回答
  •  情歌与酒
    2021-02-09 08:43

    Assuming that by fopen is disabled you mean "allow_url_fopen is disabled", a combination of CURLOPT_FILE and php://temp make this fairly easy:

    $f = fopen('php://temp', 'w+');
    
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_FILE, $f);
    // Do you need these? Your fopen() method isn't a post request
    // curl_setopt($curl, CURLOPT_POST, true);
    // curl_setopt($curl, CURLOPT_POSTFIELDS, $param);
    curl_exec($curl);
    curl_close($curl);
    
    rewind($f);
    
    while ($line = fgetcsv($f)) {
      print_r($line);
    }
    
    fclose($f);
    

    Basically this creates a pointer to a "virtual" file, and cURL stores the response in it. Then you just reset the pointer to the beginning and it can be treated as if you had opened it as usual with fopen($url, 'r');

提交回复
热议问题