Skip to content

Instantly share code, notes, and snippets.

@mgng
Last active August 3, 2016 19:18
Show Gist options
  • Select an option

  • Save mgng/4481498 to your computer and use it in GitHub Desktop.

Select an option

Save mgng/4481498 to your computer and use it in GitHub Desktop.
<?php
// エクセルファイルを zip として処理
$zip = new ZipArchive();
$zip->open( 'test.xlsx' );
// 1シート目のxml取得
$xml_sheet = simplexml_load_string( $zip->getFromName( 'xl/worksheets/sheet1.xml' ) );
// sharedStrings.xml を取得
$xml_sst = simplexml_load_string( $zip->getFromName( 'xl/sharedStrings.xml' ) );
// 結果格納用
$result = array();
// 行ループ
foreach( $xml_sheet->sheetData->row as $row ) {
// セルループ
foreach( $row->c as $cell ) {
// セルの名前。"A1" とか "B2" とか
$cell_name = (string)$cell->attributes()->r;
// セルのタイプ。文字列が設定されている場合は "s"
$cell_type = (string)$cell->attributes()->t;
// セルの値。$cell_type が "s" の場合は
// sharedStrings.xml -> si の index値が設定される。
$cell_value = (int)$cell->v;
// "s" の場合は sharedStrings.xml から取得
if ( $cell_type === 's' ) {
$cell_value = (string)$xml_sst->si[ (int)$cell->v ]->t;
}
$result[ $cell_name ] = $cell_value;
}
}
$zip->close();
print_r( $result );
Array
(
[A1] => あああ
[B1] => 111
[A2] => いいい
[B2] => 222
[A3] => ううう
[B3] => 333
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment