1 回答
TA贡献1835条经验 获得超7个赞
问题是您反复重新打开(并重新创建)CSV 文件。您可以将 'w' 更改为 'a' 以附加,或者甚至更好:将调用移至fopen()外部fclose(),foreach ($unique_id as $i => $id) {这样您就不会每次都重复重新打开文件。
当你这样做的时候,你还应该检查fopen()失败。
public function getstatusbyid()
{
$csv_file = file('C:\wamp64\www\testing\application\csv\packet.csv');
$csv_data = [];
foreach ($csv_file as $line) {
$csv_data[] = str_getcsv($line);
}
$order_no = json_encode(array_column($csv_data, '0'));
$tracking = json_encode(array_column($csv_data, '1'));
$unique_id = array_column($csv_data, '2');
$access_key = 'SOMETHING';
if ( FALSE === ( $fp = fopen('C:\wamp64\www\testing\application\csv\track.csv', 'w') ) ) {
die( "Error opening CSV file." ); // TO DO: handle this better
}
foreach ($unique_id as $i => $id) {
$url = "https://track.my/api/getstatus/$id";
$data = array(
'unique_id' => $id,
'access_key' => $access_key
);
$data_string = json_encode($data);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_TIMEOUT, 15);
$result = curl_exec($curl);
curl_close($curl);
$resultinfo = json_decode($result, true);
echo '<pre>';
print_r($resultinfo);
$status = $resultinfo["status"];
$date = $resultinfo["last_action_date_time"];
$resultdata = array();
if ($status == 'delivered') {
foreach ($resultinfo as $item) {
$resultdata[] = array(
'status' => $status,
'date' => $date
);
}
foreach ($resultdata as $fields) {
fputcsv($fp, $fields);
}
}
}
fclose($fp);
}
- 1 回答
- 0 关注
- 112 浏览
添加回答
举报