0
我通過IMAP連接從郵箱獲取XLSX附件,因此我可以使用PHPExcel將這些電子表格轉換爲PHP數組數據,但是當我加載文件並將其轉換爲數組時,數組爲空。如何使用PHPExcel讀取XLSX郵件附件文件?
這是從符合條件的郵件獲取附件功能:
public function getEmailAttachments($criteria){
$emails = imap_search($this->inbox, $criteria);
$email_attachments = [];
if($emails) {
rsort($emails);
foreach ($emails as $email_number) {
$attachments = [];
//get Email structure
$structure = imap_fetchstructure($this->inbox, $email_number);
/* if any attachments found... */
if(isset($structure->parts) && count($structure->parts))
{
for($i = 0; $i < count($structure->parts); $i++)
{
$attachments[$i] = array(
'is_attachment' => false,
'filename' => '',
'name' => '',
'attachment' => ''
);
if($structure->parts[$i]->ifdparameters)
{
foreach($structure->parts[$i]->dparameters as $object)
{
if(strtolower($object->attribute) == 'filename')
{
$attachments[$i]['is_attachment'] = true;
$attachments[$i]['filename'] = $object->value;
}
}
}
if($structure->parts[$i]->ifparameters)
{
foreach($structure->parts[$i]->parameters as $object)
{
if(strtolower($object->attribute) == 'name')
{
$attachments[$i]['is_attachment'] = true;
$attachments[$i]['name'] = $object->value;
}
}
}
if($attachments[$i]['is_attachment'])
{
$attachments[$i]['attachment'] = imap_fetchbody($this->inbox, $email_number, $i+1);
/* 3 = BASE64 encoding */
if($structure->parts[$i]->encoding == 3)
{
$attachments[$i]['attachment'] = base64_decode($attachments[$i]['attachment']);
}
/* 4 = QUOTED-PRINTABLE encoding */
elseif($structure->parts[$i]->encoding == 4)
{
$attachments[$i]['attachment'] = quoted_printable_decode($attachments[$i]['attachment']);
}
}
}
}
$email_attachments = array_merge($email_attachments, array_filter($attachments, function($attachment){return $attachment['is_attachment'] == 1;}));
}
}
imap_close($this->inbox);
return $email_attachments;
}
那麼這就是XLSX文件寫入到服務器,並加載它們與PHPExcel將它們轉換爲數組數據的功能:
public function getEmailReports(){
$this->loadPhpExcel();
$attachments = parent::getEmailAttachments('FROM "[email protected]"');
//iterate through each attachment and save it
foreach($attachments as $attachment){
$filename = $attachment['name'];
if(empty($filename)) $filename = $attachment['filename'];
$folder = "data/excel";
$file_path = "./". $folder ."/". time() . "-" . $filename;
$fp = fopen($file_path, "w");
fwrite($fp, $attachment['attachment']);
$excelReader = PHPExcel_IOFactory::createReaderForFile($file_path);
$excelObj = $excelReader->load($file_path);
foreach ($excelObj->getWorksheetIterator() as $worksheet) {
$worksheets[$worksheet->getTitle()] = $worksheet->toArray();
}
fclose($fp);
print_r($worksheets); //ARRAY IS EMPTY HERE
//unlink($file_path);
}
}
您測試過這個功能有多少? – rtfm
@rtfm XLSX文件正在成功寫入服務器,不起作用的部分是從服務器加載XLSX文件並將其轉換爲陣列時 –
沒有顯示錯誤?沒有寫入日誌? –