2011-12-08 2 views
0

나는 현재 csv 파일을 가져와 그 파일의 배열을 반환하는 함수를 가지고있다. 필자는 파일 자체 대신 파일 데이터를 가져 오기 위해 최소한이 함수를 변경하려고합니다.파일 데이터에서 리소스 핸들을 가져올 수 있습니까?

다음 코드를 사용하면 파일 대신 전달 된 데이터에서 리소스 핸들을 가져 와서 나머지 기능을 동일하게 유지할 수 있습니다. 이것이 가능한가? 당신은 파일 핸들 주위에 전달하려는 경우

public function returnRawCSVData($filepath, $separator = ',') 
{ 
    $file = fopen($filepath, 'r'); 
    $csvrawdata = array(); 

    //I WANT TO CHANGE $filepath to $file_data and get a resource from it to pass into fgetcsv below. 

    while(($row = fgetcsv($file, $this->max_row_size, $separator, $this->enclosure)) != false) {    
     if($row[0] != null) { // skip empty lines 

     } 
    } 

    fclose($file); 
    return $csvrawdata; 
} 
+0

난 당신이 단순히 *의 returnRawCSVData를 만들기 위해 찾고 있습니다 올바르게 이해 오전() * 함수는 인수로 이미 열려있는 파일의 리소스 핸들을 받아? 또는 returnRawCSVData() *로 전달할 CSV 원본 텍스트에서 리소스를 생성하려고합니까? – rdlowrey

+0

@rdlowrey 두 번째 파일 – Metropolis

답변

2

을 것 같다 당신이 소스에서 새 파일 리소스를 만들 수있는 방법을 찾고 본문?

것은 그렇다면, 당신과 같이 메모리 파일 리소스를 생성 할 수 있습니다 : PHP는 "대신 :

/** 
* Return an in-memory file resource handle from source text 
* @param string $csvtxt CSV source text 
* @return resource File resource handle 
*/ 
public static function getFileResourceFromSrcTxt($csvtxt) 
{ 
    $tmp_handle = fopen('php://temp', 'r+'); 
    fwrite($tmp_handle, $csvtxt); 
    return $tmp_handle; 
} 

/** 
* Parse csv data from source text 
* @param $file_data CSV source text 
* @see self::getFileResourceFromSrcTxt 
*/ 
public function returnRawCSVData($file_data, $separator = ',') 
{ 
    $file = self::getFileResourceFromSrcTxt($file_data); 
    $csvrawdata = array(); 

    while(($row = fgetcsv($file, $this->max_row_size, $separator, $this->enclosure)) != false) {    
    if($row[0] != null) { // skip empty lines 
     // do stuff 
    } 
    } 

    fclose($file); 
} 

그것은 당신이 또한"// 메모리 PHP는 "사용할 수있는 주목할 필요가 // 온도를 차이점은 '메모리'는 메모리에있는 것만 저장하는 반면 'temp'는 주어진 크기 (기본값은 2MB)에 도달 할 때까지 메모리에 항목을 저장 한 다음 투명하게 파일 시스템으로 전환합니다.

what the php docs say on this topic에 대해 더 알아보세요 ...

+0

이것은 기본적으로 파일 데이터를 가져 와서 임시 파일을 만들고 그 파일을 처리하는 것과 같습니다. 그것은 제가 생각한 다른 방법 이었지만 어떤 종류의 파일 생성도 피하려고했습니다. 그러나 당신의 해결책은 일시적이기 때문에 더 낫습니다. – Metropolis

+0

오른쪽 - 당신은 결코 이런 식으로 파일 시스템을 만지지 않습니다. 임시 데이터를 디스크에 저장 한 다음 삭제하는 것보다 훨씬 더 깔끔한 방법입니다. – rdlowrey

+0

대단히 감사합니다. – Metropolis

0

, 당신은 등로 처리 할 수 ​​있습니다

$in_file = fopen('some_file.csv', 'r'); 
// Do stuff with input... 

// Later, pass the file handle to a function and let it read from the file too. 
$data = doStuffWithFile($in_file); 

fclose($in_file); 


function doStuffWithFile($file_handle) 
{ 
    $line = fgetcsv($file_handle); 
    return $line; 
} 
+0

파일의 데이터가 있으므로 핸들을 전달할 수 없습니다. 원래 함수가하는 일입니다. – Metropolis

관련 문제