2013-04-13 6 views
0

symfony2 컨트롤러를 사용하여 배열을 만들고 이에 대한 응답으로 배열을 csv 파일로 반환해야 사용자가 다운로드 할 수 있습니다.이 작업을 수행하는 가장 좋은 방법은 무엇입니까? 나는symfony2의 배열에서 파일 만들기

답변

0

그것은 정말 심포니는 관련이없는 것 .. 서버에서이 파일을 저장하지 않습니다,하지만 당신은 PHP에서 아주 쉽게이 작업을 수행 할 수 있습니다

<?php 
$lines = array(
    array('foo', 'bar', 'baz'), 
    array('lorem', 'ipsum', 'dolor'), 
); 

foreach ($lines as $line) { 
    for ($i = 0; $i < count($line); $i++) { 
     echo $line[$i]; 

     if ($i < count($line) - 1) { 
      echo ","; 
     } else { 
      echo "\n"; 
     } 
    } 
} 
0

당신은 데이터의 문자열을 만들어 그것을 할 수 있습니다 Response 개체로 반환합니다. 예를 들어

귀하의 데이터, ...

$lines = array(
    array('some', 'random', 'stuff'), 
    array('in', 'an', 'array'), 
); 

도 (문자열로 결합에 사용되는 경우에 사용 인클로저를 두 번 누른 다음 라인과 필드를 통해 변수

$delimeter = ','; // Set the delimeter 
$enclosure = '"'; // Set the enclosure 
$filename = uniqid(); // Set the filename, for this a unique id 

주기를 설정 필드)

$content = ''; 

foreach ($lines as $line) 
{ 
    $fields = array(); 
    foreach ($line as $field) 
    { 
     $fields[] = $enclosure . str_replace($enclosure, 
         $enclosure . $enclosure, $field) . $enclosure; 
    } 
    $content .= implode($delimeter, $fields) . "\n"; 
} 

응답 개체를 만들고 다운로드하여 반환하십시오. 파일

$response = new Response($content); 
$response->headers->set('Content-Type', 'application/csv'); 
$response->headers->set('Content-Disposition', 
          sprintf('attachment; filename="%s.csv"', $filename)); 

return $response;