title: PHP - download CSV from external URL
body: <p>I hope you can help me...</p>
  <p>I have a provider that gives me reports by accessing a URL of this format:</p>
  <p><a href="https://data.xxx.com/api/export/%7Bid%7D/date/csv?param=1&amp;param=2" rel="nofollow noreferrer">https://data.xxx.com/api/export/{id}/date/csv?param=1&amp;param=2</a></p>
  <p>that link generates the automatic download of a .CSV</p>
  <p>What I want is to automate the downloads with a routine that builds the URLs replacing the IDs and the parameters. The resulting links work fine, but I can't get PHP to download the .CSV files and then insert them into a mySQL table.</p>
  <p>I tried with this code without success:</p>
  <pre><code>$url = &quot;https://data.xxx.com/api/export/id/date/csv?param=1&amp;param=2&quot;;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    $data = curl_exec($ch);
    curl_close($ch);
    return $data;
  </code></pre>
  <p>And with this one with no results:</p>
  <pre><code>$url = &quot;https://data.xxx.com/api/export/id/date/csv?param=1&amp;param=2&quot;;
  $opts = array(
    'http'=&gt;array(
      'method'=&gt;&quot;GET&quot;,
      'header'=&gt;&quot;Accept-language: en\r\n&quot; .
                &quot;Cookie: foo=bar.&quot;
    )
  );
  $context = stream_context_create($opts);
  $fp = fopen($url, 'r', false, $context);
  fpassthru($fp);
  fclose($fp);
  </code></pre>
  <p>I found both codes by searching the forum.
  Greetings</p>