엑셀 클립보드 내용을 PHP 배열로 변환

1 개요[ | ]

Excel Clipboard to PHP Array
PHP 엑셀 클립보드 내용을 배열로 변환
  • 엑셀에서 복사하여 textarea에 붙여넣고 [제출] 클릭

2 input.php[ | ]

<form method='post' action='output.php'>
<textarea name='my_text' style='width:500px;height:300px'></textarea>
<button>제출</button>
</form>

3 output.php[ | ]

  • 엑셀의 한 셀 내부에 개행이 있는 경우(즉 내용이 여러 줄인 경우), ____NEW_LINE____이라는 문자열로 치환해둔다.
  • 개행으로 행을 나누고, 탭으로 컬럼을 나눈다.
  • 셀 내부의 여러줄을 나타내는 시작 따옴표, 끝 따옴표를 제거하고 ____NEW_LINE____을 개행으로 복원한다.
<?php
$my_text = $_POST['my_text'];
preg_match_all('/"[^"]+"/Ui', $my_text, $out);
$need_replaces = array_unique($out[0]);

// 개행 처리
foreach($need_replaces as $need_replace) {
	$new_str = str_replace("\r\n","____NEW_LINE____", $need_replace);
	$my_text = str_replace($need_replace, $new_str, $my_text);
}
$rows = explode("\n", $my_text);
array_pop($rows);

// 탭, 따옴표 처리 + 개행 원복
foreach($rows as &$row) {
	$row = explode("\t", $row);
	foreach($row as &$cell) {
		if(strpos($cell, "____NEW_LINE____") !== false) {
			$cell = substr($cell, 1, -1);
			$cell = str_replace("____NEW_LINE____", "\n", $cell);
		}
		$cell = str_replace('""', '"', $cell);
	}
}
print_r($rows);

4 같이 보기[ | ]

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}