Created
January 9, 2014 19:13
-
-
Save wilf312/8340106 to your computer and use it in GitHub Desktop.
ExcelをPHPで読み込んで1行目を連想配列のキーにするクラス書いたよ。 ref: http://qiita.com/wilf312/items/65643f2ee300cdabbdcd
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Excelシート番号 | |
define('XLS_META', 0); // 今回使うシート | |
define('XLS_SNS', 1); | |
define('XLS_ITEM_LIST', 2); | |
// ----------------- 呼び出し | |
$scriptName = $_SERVER[“SCRIPT_NAME”]; | |
$scriptName = '/index.html'; // デバッグ用 | |
// 全体の配列を取得する | |
$metaData = EXCEL::getXls(dirname(__FILE__). '/myxls.xlsx', XLS_META); | |
// 現在のページデータ取得 | |
$pageData = $metaData[$scriptName]; | |
print '<pre>'; | |
echo '現在ページ => '. $scriptName . “\n\n”; | |
// ページデータを出力 | |
var_dump($pageData); | |
print '</pre>'; | |
// ----------------- Excel操作クラス | |
/** | |
* | |
* @author wilf312 <wilf33312@gmail.com> | |
* @create 2013/05/30 | |
* @version v 0.5 2013/05/30 02:17:19 Okada | |
**/ | |
Class Excel { | |
public static function getXls($aReadFilePath, $aSheetNum) | |
{ | |
// ライブラリファイルの読み込み | |
require_once dirname(__FILE__). "/../libs/PHPExcel/Classes/PHPExcel/IOFactory.php"; | |
// ファイルの存在チェック | |
if (!file_exists($aReadFilePath)) { | |
exit($aReadFilePath. "が見つかりません。" . EOL); | |
} | |
// xlsxをPHPExcelに食わせる | |
$objPExcel = PHPExcel_IOFactory::load($aReadFilePath); | |
// 配列形式で返す | |
return Excel::getTitleArray($objPExcel->setActiveSheetIndex($aSheetNum)->toArray(null,true,true,true)); | |
} | |
// 1行目を階層2の配列のキーにページの配列を作成 | |
// 階層2への配列アクセスはSCRIPT_NAMEを使用できるようにURLを配列のキーにする | |
public static function getTitleArray($aTableData) | |
{ | |
$titleArray = array(); | |
$keyData = array(); | |
$isFirst = true; | |
// 配列の整形 | |
foreach($aTableData as $k => $v) { | |
if ($isFirst) { | |
// タイトル行を取得 | |
$keyData = $v; | |
$isFirst = false; | |
} else { | |
$_simpleData = array(); // 仮データ保存配列 | |
// タイトル行のフィールド名を取得して配列を作成する。 | |
foreach($keyData as $k2 => $v2) { | |
// IDの場合だけ 値をfloatからintに変換しておく | |
if ($v2 === "id") { | |
$_simpleData[$v2] = (int)$v[$k2]; | |
} else { | |
$_simpleData[$v2] = $v[$k2]; | |
} | |
} | |
// 作成した配列を追加 | |
$titleArray[$_simpleData["url"]] = $_simpleData; | |
} | |
} | |
return $titleArray; | |
} | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment