将Python请求调用转换为PHP(cURL)

1 投票
1 回答
25 浏览
提问于 2025-04-13 00:17

我快要抓狂了 :)

我正在使用的公司提供了一个API,我需要用到这个API,但他们只给了我一个Python的示例。

有没有人能帮我把它转换成PHP?我试了好几次,但都没成功。我觉得问题出在文件发送上。

这是Python的代码:

import requests
import json

def send_excel_catalog_import(fname, auth_token, report_recipient_email):

api_url = f"https://www.etailpet.com/COMPANY/api/v1/catalog-update/"

payload = {"email": report_recipient_email}

files = [
    ("product_import", open(fname, "rb"))
]

headers = {"Authorization": f"Bearer {auth_token}"}

response = requests.request(
    "POST", api_url, headers=headers, data=payload, files=files
)

results_str = response.content.decode("utf8")
return response.status_code, json.loads(results_str)

if __name__ == "__main__":

    fname = "product_import.xlsx"
    send_excel_catalog_import(fname)

1 个回答

0
<?php

function send_excel_catalog_import($fname, $auth_token, $report_recipient_email) {
    $api_url = "https://www.etailpet.com/COMPANY/api/v1/catalog-update/";
    $payload = array("email" => $report_recipient_email);
    $files = array(
        "product_import" => new CURLFile($fname)
    );
    $headers = array("Authorization: Bearer $auth_token");

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $api_url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, array_merge($payload, $files));
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $response = curl_exec($ch);
    $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    curl_close($ch);

    return array($status_code, json_decode($response, true));
}

// Usage example
$fname = "product_import.xlsx";
$auth_token = "your_auth_token_here";
$report_recipient_email = "recipient@example.com";

list($status_code, $results) = send_excel_catalog_import($fname, $auth_token, $report_recipient_email);

echo "Status Code: $status_code\n";
echo "Results: " . print_r($results, true) . "\n";
?>

确保把“your_auth_token_here”换成你真实的授权令牌。另外,要确认文件路径product_import.xlsx是正确的。

撰写回答