【问题标题】:Upload a CSV file via PHP Curl通过 PHP Curl 上传 CSV 文件
【发布时间】:2017-10-25 17:30:14
【问题描述】:

我确信这个问题已经被问过很多次了,但我不知道为什么我的 php 脚本不起作用。我有一个 CSV 文件,当我使用以下命令行 curl 上传它时,我知道它可以完美运行:

curl -H 'Content-Type: text/csv' --data-binary @/Users/johndoe/Downloads/payables.csv -H "Authorization: Bearer [some_token_key]" 'https://example.com/api/v1/imports.json'

当我尝试将此命令转换为 PHP Curl 时,这是我的 php 脚本:

$file = "/Users/johndoe/Downloads/payables.csv";
$authorization = "Authorization: Bearer [some_token_key]";

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "https://example.org/api/v1/imports.json");
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_HTTPHEADER, [$authorization, 'Content-Type: text/csv']);
$cfile = new CurlFile($file,  'text/csv');
$data = array('data-binary' => realpath($cfile));
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$curl_response = curl_exec($curl);
curl_close($curl);

有人看到我的 PHP 脚本有什么问题吗?我正在使用 php 5.5,我在尝试处理 CSV 文件的接收站点上看到的错误是它找不到 CSV 导入标头。这没有任何意义。有什么想法吗?

【问题讨论】:

  • 我认为您的 php 脚本无法从 /Users/johndoe/Downloads/payables.csv 读取文件,请将其放在根目录中,即您的 php 脚本所在的位置并尝试
  • @sumit 没用。我将文件放在我的应用程序的根目录中,什么也没有。同样的错误。

标签: php csv curl file-upload


【解决方案1】:

不要尝试访问您的下载文件夹,而是上传项目目录中的文件,然后将其传递到 curl。

move_uploaded_file($_FILES['file']['tmp_name'], __DIR__.'/uploads/'. $_FILES["image"]['name']);

$file = "uploads/payables.csv";
$authorization = "Authorization: Bearer [some_token_key]";

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "https://example.org/api/v1/imports.json");
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_HTTPHEADER, [$authorization, 'Content-Type: text/csv']);
$cfile = new CurlFile($file,  'text/csv');
//curl file itself return the realpath with prefix of @
$data = array('data-binary' => $cfile);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$curl_response = curl_exec($curl);
curl_close($curl);

【讨论】:

    猜你喜欢
    • 2016-02-22
    • 2016-03-19
    • 2011-08-04
    • 1970-01-01
    • 2019-05-29
    • 2012-11-24
    • 1970-01-01
    • 1970-01-01
    • 2020-01-05
    相关资源
    最近更新 更多