我希望能在這裏找到一些PHPExcel用戶,因爲他們討論組中的活動似乎有點悠閒:)。 (我的原始郵件can be seen here)PHPExcel - 我的CSV自動解碼器:我可以在解析之前訪問orig上傳的文件嗎?
我抓到了一個功能,用於自動檢測CSV文件的分隔符和/或附件。
現在它正在運行,我想將它插入PHPExcel(通過擴展CSV類)。
我唯一的問題是,我的面向對象的技能非常年輕,而且我在查找如何/在哪裏集成它有點麻煩。
我的函數當前需要通過file()
創建的數組,但是如果需要,我可以輕鬆更改它。
function autoDetect(array $file, array $toDetect=array(true,false), $sampleSize=5){
$detectDelim = $toDetect[0]? true: false;
$detectEncl = $toDetect[1]? true: false;
$sampleSize = (count($file) < $sampleSize)? count($file): $sampleSize; // set sample-size to the lesser value
array_splice($file, $sampleSize); // trim down the array to only first X rows
$delimiters = array(',','^','.',';',':',"\t"); // first elem will be the dflt
$delimRegex = implode('',$delimiters);
$enclosures = array('"',"'",'^'); // first elem will be the dflt
$enclRegex = implode('',$enclosures);
foreach ($file as $row) {
$row=preg_replace('/\r\n/', '', trim($row)); // clean up .. strip new line and line return chars
if($detectDelim){
$stripped=preg_replace("/[^$delimRegex]/", '', $row); // clean up .. strip evthg x'ept dilim's
$delimRowChars = str_split($stripped); // get each char so we can inspect individually
$delimCount = _count_instances($delimRowChars, $delimiters); // TODO : fix how this overwrites itself
// TODO : set delim
}
if($detectEncl){
$stripped=preg_replace("/[^$enclRegex]/", '', $row); // clean up .. strip evthg x'ept dilim's
$enclRowChars = str_split($stripped); // get each char so we can inspect individually
$enclCount = _count_instances($enclRowChars, $enclosures); // TODO : fix how this overwrites itself
// TODO : set encl
}
}
echo'<pre>delims found in sample set: ', print_r($delimCount), '</pre>'; // For Testing ---->
echo'<pre>encls found in sample set: ', print_r($enclCount), '</pre>'; // For Testing ---->
echo "<pre>Suggested Delimiter: '",_array_max($delimCount),"' </pre>"; // For Testing ---->
echo "<pre>Suggested Enclosure: '",_array_max($enclCount),"' </pre>"; // For Testing ---->
//return TODO ;
}
/**
*
*/
function _count_instances(array $haystacks, array $needles, $maxOnly = false){
$basket = array(); // instantiate
foreach ($haystacks as $haystack) {
foreach ($needles as $needle) { // this throws an undef'd index err and adds an element to the array
if(strpos($haystack, $needle) !== false) { // if the needle is in the haystack ...
if($needle == "\t") $needle = '\t'; // TODO : decouple this from "\t" so it can work for other chars too
$basket[$needle]++; // ... increment
}
}
}
if($maxOnly) $basket = _array_max($basket);
return $basket;
}
/**
*
*/
function _array_max(array $target){
$target = array_keys($target, max($target));
$target = $target[0];
return $target;
}
我只需要在文件被解析之前運行我的自動檢測器,並且我沒有看到對象中的信息。
何時/如何/如何插入? 有沒有訪問原始文件,或?