Explorar el Código

Dodanie funkcji Response::sendCsv (plik CSV do pobrania)

Mariusz Muszyński hace 8 años
padre
commit
bd0122b435
Se han modificado 1 ficheros con 18 adiciones y 0 borrados
  1. 18 0
      SE/se-lib/Response.php

+ 18 - 0
SE/se-lib/Response.php

@@ -13,6 +13,11 @@ Lib::loadClass('DBG');
  */
 class Response {
 
+	public static function correctFilename($filename, $extension = null) {
+		if (strlen($extension) && (!preg_match("/\.{$extension}$/i", $filename))) $filename .= ".{$extension}";
+		return preg_replace('/[^[:alnum:].-]/', '_', $filename);
+	}
+
 	public static function sendJson($data) {
 		header("Content-type: application/json");
 		echo json_encode($data);
@@ -24,6 +29,14 @@ class Response {
 		echo $data;
 	}
 
+	public static function sendCsv($data, $filename = null) {
+		header("Content-Type: text/csv");
+		if (strlen($filename)) header('Content-Disposition: attachment; filename=' . self::correctFilename($filename, 'csv') . ';');
+		header("Content-Transfer-Encoding: binary");
+		header("Content-Length: ".strlen($data));
+		echo $data;
+	}
+
 
 	public static function sendJsonExit($data) {
 		self::sendJson($data);
@@ -35,6 +48,11 @@ class Response {
 		exit;
 	}
 
+	public static function sendCsvExit($data, $fileName = null) {
+		self::sendCsvExit($data, $fileName);
+		exit;
+	}
+
 	public static function sendTryCatchJson($callback, $args = array()) {// @param callback must return $response object to send as json or throw exception
 		$response = array();
 		try {