Exemplo n.º 1
0
 /**
  * {@inheritdoc}
  * @param array|Traversable $row The row to write
  */
 public function writeRow($row)
 {
     if ($row instanceof \Traversable) {
         $row = iterator_to_array($row);
     }
     $this->fileObject->fputcsv(is_array($row) ? $row : [$row]);
 }
Exemplo n.º 2
0
 /**
  * Converts all objects in a collection to CSV and saves them to the FILENAME constant of the collection
  * @param string $path the base path to write to; e.g. 'gtfs/'
  * @param mixed $collection A collection of GTFS objects
  * @return void
  */
 public static function write($path, $collection)
 {
     if ($collection->count()) {
         $file = new \SplFileObject($path . $collection::FILENAME, 'w+');
         $file->fputcsv(array_keys($collection->getFirst()->__toArray()));
         foreach ($collection as $object) {
             $file->fputcsv($object->__toArray());
         }
     }
 }
Exemplo n.º 3
0
 /**
  * Adds a single line to a CSV document
  *
  * @param string[]|string $row a string, an array or an object implementing to '__toString' method
  *
  * @return static
  */
 public function insertOne($row)
 {
     if (!is_array($row)) {
         $row = str_getcsv($row, $this->delimiter, $this->enclosure, $this->escape);
     }
     $row = $this->formatRow($row);
     $this->validateRow($row);
     if (is_null($this->csv)) {
         $this->csv = $this->getIterator();
     }
     $this->csv->fputcsv($row, $this->delimiter, $this->enclosure);
     if ("\n" !== $this->newline) {
         $this->csv->fseek(-1, SEEK_CUR);
         $this->csv->fwrite($this->newline);
     }
     return $this;
 }
 /**
  * フィールドの配列をCSVの行として書き出します。
  * @param \SplFileObject $file
  * @param string[] $fields
  */
 protected function putCSVRecord(\SplFileObject $file, array $fields)
 {
     $file->fputcsv(array_map(function (string $field) : string {
         return preg_replace('/[\\x00-\\x09\\x11\\x7F]+/u', '', strtr($field, ["\r\n" => "\r\n", "\r" => "\r\n", "\n" => "\r\n"]));
     }, $fields));
     $file->fseek(-1, SEEK_CUR);
     $file->fwrite("\r\n");
 }
Exemplo n.º 5
0
 private function _write()
 {
     $this->_file->ftruncate(0);
     foreach ($this->_data as $domain => $stats) {
         foreach ($stats as $date => $row) {
             $this->_file->fputcsv([$domain, $date] + $row);
         }
     }
 }
Exemplo n.º 6
0
 public function postIndex(Request $request)
 {
     // dump($request->input());
     $faker = Faker::create();
     $num_users = $request->input('num_users');
     $address = $request->input('address');
     if ($address == 'on') {
         $this->formdata['address_yes'] = 'checked';
     }
     $phone = $request->input('phone');
     if ($phone == 'on') {
         $this->formdata['phone_yes'] = 'checked';
     }
     $photo = $request->input('photo');
     if ($photo == 'on') {
         $this->formdata['photo_yes'] = 'checked';
     }
     for ($i = 0; $i < $num_users; $i++) {
         $users[$i]['name'] = $faker->name;
         $users[$i]['username'] = "******" . $faker->username;
         if ($i % 2 == 0) {
             $fname = $faker->firstName;
             $lname = $faker->lastName;
             $email = strtolower(substr($fname, 0, 1)) . $lname . "@" . $faker->freeEmailDomain;
             $users[$i]['name'] = $fname . " " . $lname;
             $users[$i]['email'] = $email;
         } else {
             $users[$i]['email'] = $faker->email;
         }
         if ($address == 'on') {
             $users[$i]['streetaddress'] = $faker->streetAddress;
             $users[$i]['city'] = $faker->city;
             $users[$i]['postcode'] = $faker->postcode;
             $users[$i]['state'] = $faker->stateAbbr;
         }
         if ($phone == 'on') {
             $users[$i]['phone'] = $faker->phoneNumber;
         }
         if ($photo == 'on') {
             $users[$i]['photo'] = $faker->imageUrl($width = 200, $height = 200, 'animals');
         }
     }
     $jsonpath = public_path();
     $jsonpath .= '/downloads/randomusers.json';
     $json = fopen($jsonpath, 'w');
     fwrite($json, json_encode($users));
     fclose($json);
     $csv = new \SplFileObject('downloads/randomusers.csv', 'w');
     foreach ($users as $user) {
         $csv->fputcsv($user);
     }
     return view('user_generator')->with('users', $users)->with('formdata', $this->formdata);
 }
Exemplo n.º 7
0
 public function export(TableView $view, $template = null, array $options = array())
 {
     $out = tempnam('/tmp', 'export-out-');
     $data = $view->getData();
     $file = new \SplFileObject($out, 'w');
     $file->setCsvControl($this->delimiter, $this->enclosure, $this->escape);
     $row = array();
     foreach ($data['thead'] as $th) {
         $row[] = $th['title'];
     }
     $file->fputcsv($row);
     foreach ($data['tbody'] as $tr) {
         $row = array();
         foreach ($tr['data'] as $td) {
             $row[] = $td['value'];
         }
         $file->fputcsv($row);
     }
     $now = new \DateTime();
     $filename = preg_replace(array('/\\[now\\]/', '/\\[caption\\]/'), array($now->format('Y-m-d H\\hi'), $data['caption']), 'Export');
     return new Export($file->getFileInfo(), $this->getContentType(), $filename, $this->getFileExtension());
 }
<?php

$fo = new SplFileObject(__DIR__ . '/SplFileObject_fputcsv1.csv', 'w');
$data = array(1, 2, 'foo', 'haha', array(4, 5, 6), 1.3, null);
$fo->fputcsv($data);
var_dump($data);
Exemplo n.º 9
0
function createMrpException($itemKeyValues)
{
    global $mrpExceptionDir, $isMrpHeaderAdded, $itemMasterFields, $itemDistributorFields, $mrpExcepFile;
    if (!$isMrpHeaderAdded) {
        $mrpExcepFile = new SplFileObject($mrpExceptionDir, 'w');
        $mrpExcepFile->fputcsv(array_merge($itemMasterFields, $itemDistributorFields));
        $isMrpHeaderAdded = true;
    }
    $mrpExcepFile->fputcsv($itemKeyValues);
}
Exemplo n.º 10
0
 public function generateTradeFileAction(Request $request)
 {
     $ria = $this->getUser();
     /** @var RiaCompanyInformation $riaCompanyInformation */
     $riaCompanyInformation = $ria->getRiaCompanyInformation();
     $isHouseholdLevel = $riaCompanyInformation->isHouseholdManagedLevel();
     $formValues = $request->get('rebalance_form');
     $clientPortfolioValuesManager = $this->get('wealthbot_client.client_portfolio_values.manager');
     $clientAccountValuesManager = $this->get('wealthbot_client.client_account_values.manager');
     $clientPortfolioManager = $this->get('wealthbot_client.client_portfolio.manager');
     $rebalancerQueueManager = $this->get('wealthbot.manager.rebalancer_queue');
     if (isset($formValues['is_all']) && $formValues['is_all']) {
         if ($isHouseholdLevel) {
             $clientValues = $clientPortfolioValuesManager->getLatestClientPortfolioValuesForClients($ria);
         } else {
             $clientValues = $clientAccountValuesManager->getLatestClientAccountValuesForClients($ria, $clientPortfolioManager);
         }
         $clientValuesIds = array();
         foreach ($clientValues as $clientValue) {
             $clientValuesIds[] = $clientValue->getId();
         }
     } else {
         $clientValuesIds = $formValues['client_value'];
     }
     if (!$request->isXmlHttpRequest() || empty($clientValuesIds)) {
         throw $this->createNotFoundException();
     }
     $form = $this->createForm(new RebalanceFormType($clientValuesIds, true));
     $form->bind($request);
     if ($form->isValid()) {
         $tradeDataCollection = $rebalancerQueueManager->getTradeDataCollection($riaCompanyInformation, $clientValuesIds);
         if (empty($tradeDataCollection)) {
             return $this->getJsonResponse(array('status' => 'error', 'message' => 'No Trades'));
         }
         $date = date('mdY-His');
         $filename = $date . '.csv';
         $filePath = $this->container->getParameter('uploads_trade_files_dir') . '/' . $filename;
         $file = new \SplFileObject($filePath, 'w');
         foreach ($tradeDataCollection as $tradeData) {
             $file->fputcsv($tradeData->toArrayForTradeFile());
             if ($tradeData->getAction() === RebalancerQueue::STATUS_SELL) {
                 foreach ($tradeData->getVsps() as $vsp) {
                     $file->fputcsv($vsp);
                 }
             }
         }
         return $this->getJsonResponse(array('status' => 'success', 'redirect_url' => $this->generateUrl('rx_download_trade_file', array('filename' => $filename))));
     }
     return $this->getJsonResponse(array('status' => 'error', 'message' => 'Invalid Data'));
 }
     $s1->setFlags(SplFileObject::SKIP_EMPTY | SplFileObject::DROP_NEW_LINE);
     if ($s1->isFile() && $s1->isReadable()) {
         $s1->seek(1);
         while ($row = $s1->fgetcsv($delimieter[0])) {
             $data = array($row[7], $row[8]);
             if (!in_array($data, $values)) {
                 $values[] = $data;
             }
         }
         unset($row);
         usort($values, function ($a, $b) {
             return $a[0] > $b[0];
         });
         try {
             $s2 = new SplFileObject($argv[2], 'w');
             $s2->fputcsv(array('id', 'code'), $delimieter[1]);
             foreach ($values as $data) {
                 $s2->fputcsv($data, "\t");
             }
         } catch (RuntimeException $e) {
             echo $e->getMessage();
             exit($e->severity);
         } finally {
             unset($s2);
         }
         unset($data, $values);
     }
 } catch (RuntimeException $e) {
     echo $e->getMessage();
     exit($e->severity);
 }
Exemplo n.º 12
0
 /**
  * Tries to create the file.
  *
  * If it already exists - throw an exception.
  * After creating it puts into file row with column headers.
  *
  * @param $filename
  * @param $fileConfig
  * @param null $delimiter
  * @return bool
  * @throws \Exception
  */
 public function create($filename, $fileConfig, $delimiter = null)
 {
     if ($this->has($filename)) {
         throw new \Exception("The file \"{$filename}\" already exists. Use \"rewrite()\" instead.");
     }
     $filename = $this->getRealFileName($filename);
     $delimiter = !is_null($delimiter) ?: self::DELIMITER_BY_DEFAULT;
     try {
         $file = new \SplFileObject($filename, 'w');
         $file->fputcsv($fileConfig, $delimiter);
     } catch (\Exception $e) {
         return false;
     } finally {
         // Close file
         unset($file);
         // Make garbage the cycle that the closing file was done immediately.
         gc_collect_cycles();
     }
     return true;
 }
<?php

$dados = array(array('codigo', 'nome', 'endereco', 'telefone'), array('1', 'Maria da Silva', 'Rua da Maria', '(11) 12345678'), array('2', 'Pedro Cardoso', 'Rua do Pedro', '(11) 12345678'), array('3', 'Joana Pereira', 'Rua da Joana', '(11) 12345678'));
$file = new SplFileObject('dados.csv', 'w');
$file->setCsvControl(',');
foreach ($dados as $linha) {
    $file->fputcsv($linha);
}
Exemplo n.º 14
0
 /**
  * Responds to requests to POST /users
  */
 public function postIndex(Request $request)
 {
     $faker = Faker::create();
     $this->validate($request, ['numusers' => 'required|numeric|min:1|max:10']);
     $numusers = $request->input('numusers');
     $this->formdata['numusers'] = $numusers;
     $address = $request->input('address');
     if ($address == 'on') {
         $this->formdata['addressyes'] = 'checked';
     }
     $phone = $request->input('phone');
     if ($phone == 'on') {
         $this->formdata['phoneyes'] = 'checked';
     }
     $birthday = $request->input('birthday');
     if ($birthday == 'on') {
         $this->formdata['birthdayyes'] = 'checked';
     }
     $profile = $request->input('profile');
     if ($profile == 'on') {
         $this->formdata['profileyes'] = 'checked';
     }
     $photo = $request->input('photo');
     if ($photo == 'on') {
         $this->formdata['photoyes'] = 'checked';
     }
     for ($i = 0; $i < $numusers; $i++) {
         $users[$i]['name'] = $faker->name;
         $users[$i]['username'] = $faker->username;
         $users[$i]['email'] = $faker->email;
         if ($address == 'on') {
             $users[$i]['streetaddress'] = $faker->streetAddress;
             $users[$i]['city'] = $faker->city;
             $users[$i]['postcode'] = $faker->postcode;
             $users[$i]['state'] = $faker->stateAbbr;
         }
         if ($phone == 'on') {
             $users[$i]['phone'] = $faker->phoneNumber;
         }
         if ($birthday == 'on') {
             /*  
                 note: setting minimum age of fake users to 13
                 to avoid COPPA complications: http://www.coppa.org/
             */
             $users[$i]['birthday'] = $faker->date($format = 'Y-m-d', $max = '2002-10-21');
         }
         if ($profile == 'on') {
             $users[$i]['profile'] = $faker->text($maxNbChars = 140);
         }
         if ($photo == 'on') {
             $users[$i]['photo'] = $faker->imageUrl($width = 200, $height = 200, 'cats');
         }
     }
     $json = fopen('downloads/randomusers.json', 'w');
     fwrite($json, json_encode($users));
     fclose($json);
     $csv = new \SplFileObject('downloads/randomusers.csv', 'w');
     foreach ($users as $user) {
         $csv->fputcsv($user);
     }
     return view('users')->with('users', $users)->with('formdata', $this->formdata);
 }
Exemplo n.º 15
0
$export_query .= $_SESSION['where'];
$export_result = mysqli_query($dbc, $export_query) or die('Error querying database.');
if (isset($_POST['csv_export'])) {
    // ファイル名
    $file_path = '../../tmp/user_list.csv';
    // CSVに出力するタイトル行
    $export_csv_title = array('No.', '姓', '名', 'メールアドレス', 'ユーザID', 'パスワード', '生年月日', '性別');
    if (touch($file_path)) {
        // オブジェクト生成
        $file = new SplFileObject($file_path, 'w');
        // タイトル行のエンコードをSJIS-winに変換
        foreach ($export_csv_title as $key => $val) {
            $export_header[] = mb_convert_encoding($val, 'SJIS-win', 'UTF-8');
        }
        // エンコードしたタイトル行を配列ごとCSVデータ化
        $file->fputcsv($export_header);
        while ($row_export = mysqli_fetch_assoc($export_result)) {
            $export_arr = '';
            // 内容行のエンコードをSJIS-winに変換
            foreach ($row_export as $key => $val) {
                $export_arr[] = mb_convert_encoding($val, 'SJIS-win', 'UTF-8');
            }
            // エンコードした内容行を配列ごとCSVデータ化
            $file->fputcsv($export_arr);
        }
    }
    // ダウンロード
    header('Pragma: public');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Cache-Control: private', false);
Exemplo n.º 16
0
 public static function createCSV($arrayCSV, $nameFile, $path)
 {
     //$csv = new SplFileObject('../../modules/cityData/fileCityData/'.$file['fileimport']['name'].'_'.$countFile.'.csv', 'w');
     $csv = new SplFileObject($path . $nameFile, 'w');
     foreach ($arrayCSV as $lineCSV) {
         $csv->fputcsv($lineCSV);
     }
 }
$file = "{$file_path}/fputcsv_variation11.tmp";
$file_modes = array("r+", "r+b", "r+t", "a+", "a+b", "a+t", "w+", "w+b", "w+t", "x+", "x+b", "x+t");
$loop_counter = 1;
foreach ($csv_lists as $csv_list) {
    for ($mode_counter = 0; $mode_counter < count($file_modes); $mode_counter++) {
        echo "\n-- file opened in {$file_modes[$mode_counter]} --\n";
        // create the file and add the content with has csv fields
        if (strstr($file_modes[$mode_counter], "r")) {
            $fo = new SplFileObject($file, 'w');
        } else {
            $fo = new SplFileObject($file, $file_modes[$mode_counter]);
        }
        $delimiter = $csv_list[0];
        $enclosure = $csv_list[1];
        $csv_field = $csv_list[2];
        // write to a file in csv format
        var_dump($fo->fputcsv($csv_field, $delimiter));
        // check the file pointer position and eof
        var_dump($fo->ftell());
        var_dump($fo->eof());
        //close the file
        unset($fo);
        // print the file contents
        var_dump(file_get_contents($file));
        //delete file
        unlink($file);
    }
    //end of mode loop
}
// end of foreach
echo "Done\n";
Exemplo n.º 18
0
 public function unlockTasks(array $tasks = null)
 {
     $logger = Logger::getLogger('file-queue');
     $logger->info('unlock tasks');
     if ($tasks === null) {
         $tasks = $this->tasks;
     }
     $statusFileObject = $this->getStatusFileObject();
     if (!$statusFileObject->flock(LOCK_EX)) {
         throw new \RuntimeException("Can't get lock for status file {$this->getStatusFile()}");
     }
     $tasksFileObject = new \SplFileObject($this->getTasksFile(), 'a');
     foreach ($tasks as $task) {
         if ($tasksFileObject->fputcsv([$task->getId(), $task->getData()]) === false) {
             throw new \RuntimeException("Can't write task to tasks file {$this->getTasksFile()}");
         }
     }
     if (!$statusFileObject->flock(LOCK_UN)) {
         $logger->warn("Can't release lock");
     }
 }
$file = "{$file_path}/fputcsv_variation6.tmp";
$file_modes = array("r+", "r+b", "r+t", "a+", "a+b", "a+t", "w+", "w+b", "w+t", "x+", "x+b", "x+t");
$loop_counter = 1;
foreach ($csv_lists as $csv_list) {
    for ($mode_counter = 0; $mode_counter < count($file_modes); $mode_counter++) {
        echo "\n-- file opened in {$file_modes[$mode_counter]} --\n";
        // create the file and add the content with has csv fields
        if (strstr($file_modes[$mode_counter], "r")) {
            $fo = new SplFileObject($file, 'w');
        } else {
            $fo = new SplFileObject($file, $file_modes[$mode_counter]);
        }
        $delimiter = $csv_list[0];
        $enclosure = $csv_list[1];
        $csv_field = $csv_list[2];
        // write to a file in csv format
        var_dump($fo->fputcsv($csv_field, '+', '%'));
        // check the file pointer position and eof
        var_dump($fo->ftell());
        var_dump($fo->eof());
        //close the file
        unset($fo);
        // print the file contents
        var_dump(file_get_contents($file));
        //delete file
        unlink($file);
    }
    //end of mode loop
}
// end of foreach
echo "Done\n";
$file = "{$file_path}/fputcsv_variation7.tmp";
$file_modes = array("r+", "r+b", "r+t", "a+", "a+b", "a+t", "w+", "w+b", "w+t", "x+", "x+b", "x+t");
$loop_counter = 1;
foreach ($csv_lists as $csv_list) {
    for ($mode_counter = 0; $mode_counter < count($file_modes); $mode_counter++) {
        echo "\n-- file opened in {$file_modes[$mode_counter]} --\n";
        // create the file and add the content with has csv fields
        if (strstr($file_modes[$mode_counter], "r")) {
            $fo = new SplFileObject($file, 'w');
        } else {
            $fo = new SplFileObject($file, $file_modes[$mode_counter]);
        }
        $delimiter = $csv_list[0];
        $enclosure = $csv_list[1];
        $csv_field = $csv_list[2];
        // write to a file in csv format
        var_dump($fo->fputcsv($csv_field, '+', $enclosure));
        // check the file pointer position and eof
        var_dump($fo->ftell());
        var_dump($fo->eof());
        //close the file
        unset($fo);
        // print the file contents
        var_dump(file_get_contents($file));
        //delete file
        unlink($file);
    }
    //end of mode loop
}
// end of foreach
echo "Done\n";
Exemplo n.º 21
0
 /**
  * Writes the record data from memory into the file store.
  *
  * @return void
  */
 public function save()
 {
     $tmpHandle = new \SplFileObject('php://temp', 'w+');
     $tmpData = '';
     $tmpHandle->fputcsv($this->model->columns());
     foreach ($this->all() as $record) {
         $tmpHandle->fputcsv($record->toArray());
         $record->exists = true;
     }
     $tmpHandle->rewind();
     while (!$tmpHandle->eof()) {
         $tmpData .= $tmpHandle->fgets();
     }
     $this->file->flock(\LOCK_EX | \LOCK_NB);
     $this->file->ftruncate(0);
     $this->file->rewind();
     $this->file->fwrite($tmpData);
     $this->file->flock(\LOCK_UN);
 }
<?php

/* Testing fputcsv() to write to a file when default enclosure value and delimiter
   of two chars is provided and file is opened in read only mode */
echo "*** Testing fputcsv() : with enclosure & delimiter of two chars and file opened in read mode ***\n";
$fo = new SplFileObject(__DIR__ . '/SplFileObject_fputcsv_variation14.csv', 'w');
var_dump($fo->fputcsv(array('water', 'fruit'), ',,', '""'));
unset($fo);
echo "Done\n";
error_reporting(0);
$file = __DIR__ . '/SplFileObject_fputcsv_variation14.csv';
unlink($file);
Exemplo n.º 23
0
 public function generateTradeFile()
 {
     $date = date('mdY-His');
     $path = __DIR__ . '/../outgoing_files/trade_files/' . $date . '.csv';
     $file = new \SplFileObject($path, 'w');
     /** @var RebalancerQueueRepository $rebalancerQueueRepo */
     $rebalancerQueueRepo = $this->getRepository('RebalancerQueue');
     $tradeDataCollection = $rebalancerQueueRepo->getTradeDataCollectionForJob($this->getJob());
     /** @var TradeData $tradeData */
     foreach ($tradeDataCollection as $tradeData) {
         $file->fputcsv($tradeData->toArrayForTradeFile());
         if ($tradeData->getAction() === TradeData::ACTION_SELL) {
             foreach ($tradeData->getVsps() as $vsp) {
                 $file->fputcsv($vsp);
             }
         }
     }
 }
Exemplo n.º 24
0
 /**
  * Post a file to myMemory
  *
  * Remove the first line from csv ( source and target )
  * and rewrite the csv because MyMemory doesn't want the header line
  *
  * @param            $file
  * @param            $key
  * @param bool|false $name
  *
  * @return Engines_Results_MyMemory_TmxResponse
  */
 public function glossaryImport($file, $key, $name = false)
 {
     try {
         $origFile = new SplFileObject($file, 'r+');
         $origFile->setFlags(SplFileObject::READ_CSV | SplFileObject::SKIP_EMPTY | SplFileObject::READ_AHEAD);
         $tmpFileName = tempnam("/tmp", 'GLOS');
         $newFile = new SplFileObject($tmpFileName, 'r+');
         $newFile->setFlags(SplFileObject::READ_CSV | SplFileObject::SKIP_EMPTY | SplFileObject::READ_AHEAD);
         foreach ($origFile as $line_num => $line) {
             if (count($line) < 2) {
                 throw new RuntimeException("No valid glossary file provided. Field separator could be not valid.");
             }
             if ($line_num == 0) {
                 list($source_lang, $target_lang, ) = $line;
                 //eventually, remove BOM from source language
                 $bom = pack('H*', 'EFBBBF');
                 $source_lang = preg_replace("/^{$bom}/", "", $source_lang);
                 if (!Langs_Languages::isEnabled($source_lang)) {
                     throw new RuntimeException("The source language specified in the glossary is not supported: " . $source_lang);
                 }
                 if (!Langs_Languages::isEnabled($target_lang)) {
                     throw new RuntimeException("The target language specified in the glossary is not supported: " . $target_lang);
                 }
                 if (empty($source_lang) || empty($target_lang)) {
                     throw new RuntimeException("No language definition found in glossary file.");
                 }
                 continue;
             }
             //copy stream to stream
             $newFile->fputcsv($line);
         }
         $newFile->fflush();
         $origFile = null;
         //close the file handle
         $newFile = null;
         //close the file handle
         copy($tmpFileName, $file);
         unlink($tmpFileName);
     } catch (RuntimeException $e) {
         $this->result = new Engines_Results_MyMemory_TmxResponse(array("responseStatus" => 406, "responseData" => null, "responseDetails" => $e->getMessage()));
         return $this->result;
     }
     $postFields = array('glossary' => "@" . realpath($file), 'source_lang' => $source_lang, 'target_lang' => $target_lang, 'name' => $name);
     $postFields['key'] = trim($key);
     $this->call("glossary_import_relative_url", $postFields, true);
     return $this->result;
 }
Exemplo n.º 25
0
 private function createGeom($shpFile, SplFileObject $tmpCsvFile)
 {
     // get feature count
     \ob_start();
     $cmd = 'ogrinfo  -so ' . \escapeshellarg($shpFile) . '  tl_2015_us_state';
     \common\logging\Logger::obj()->write('Running command: ' . $cmd);
     \passthru($cmd, $ret);
     $output = \ob_get_contents();
     \ob_end_clean();
     if (\preg_match('/Feature\\sCount:\\s(\\d+)/', $output, $matches) === 1 && ($fids = \filter_var($matches[1], \FILTER_VALIDATE_INT))) {
         \common\logging\Logger::obj()->write('Features: ' . $fids);
         for ($fid = 0; $fid < $fids; $fid++) {
             \ob_start();
             $cmd = 'ogrinfo -fid ' . $fid . ' ' . \escapeshellarg($shpFile) . ' tl_2015_us_state';
             \common\logging\Logger::obj()->write('Running command: ' . $cmd);
             \passthru($cmd, $ret);
             $output = \trim(\ob_get_contents());
             if ($ret >= 0 && \preg_match('/\\s\\sSTATEFP\\s\\(String\\)\\s=\\s(\\d+)/', $output, $matchesStatefp) === 1 && \preg_match('/((MULTIPOLYGON|POLYGON)\\s\\(.*\\))/', $output, $matchesPolygon) === 1) {
                 \common\logging\Logger::obj()->write('Writing Feature: ' . $fid);
                 $tmpCsvFile->fputcsv([$matchesStatefp[1], $matchesPolygon[1]]);
                 unset($matchesPolygon, $matchesStatefp);
             } else {
                 echo "Unable to write feature {$fid} to output file\n";
             }
             \ob_end_clean();
         }
     } else {
         echo "Unable to determine the feature count of the shape file\n";
         exit((int) ('-' . __LINE__));
     }
     unset($output);
     return $ret;
 }
$fields = array(array('water_fruit\\n'), array("water_fruit\n"), array(""));
$file_path = dirname(__FILE__);
$file = "{$file_path}/fputcsv_variation10.tmp";
$file_modes = array("r+", "r+b", "r+t", "a+", "a+b", "a+t", "w+", "w+b", "w+t", "x+", "x+b", "x+t");
$loop_counter = 1;
foreach ($fields as $field) {
    for ($mode_counter = 0; $mode_counter < count($file_modes); $mode_counter++) {
        echo "\n-- file opened in {$file_modes[$mode_counter]} --\n";
        // create the file and add the content with has csv fields
        if (strstr($file_modes[$mode_counter], "r")) {
            $fo = new SplFileObject($file, 'w');
        } else {
            $fo = new SplFileObject($file, $file_modes[$mode_counter]);
        }
        $csv_field = $field;
        // write to a file in csv format
        var_dump($fo->fputcsv($csv_field));
        // check the file pointer position and eof
        var_dump($fo->ftell());
        var_dump($fo->eof());
        //close the file
        unset($fo);
        // print the file contents
        var_dump(file_get_contents($file));
        //delete file
        unlink($file);
    }
    //end of mode loop
}
// end of foreach
echo "Done\n";
$file_path = dirname(__FILE__);
$file = "{$file_path}/fputcsv_variation1.tmp";
$file_modes = array("r+", "r+b", "r+t", "a+", "a+b", "a+t", "w+", "w+b", "w+t", "x+", "x+b", "x+t");
$loop_counter = 1;
foreach ($csv_lists as $csv_list) {
    for ($mode_counter = 0; $mode_counter < count($file_modes); $mode_counter++) {
        echo "\n-- file opened in {$file_modes[$mode_counter]} --\n";
        // create the file and add the content with has csv fields
        if (strstr($file_modes[$mode_counter], "r")) {
            $fo = new SplFileObject($file, 'w');
        } else {
            $fo = new SplFileObject($file, $file_modes[$mode_counter]);
        }
        $delimiter = $csv_list[0];
        $enclosure = $csv_list[1];
        $csv_field = $csv_list[2];
        var_dump($fo->fputcsv($csv_field, $delimiter, $enclosure));
        // check the file pointer position and eof
        var_dump($fo->ftell());
        var_dump($fo->eof());
        //close the file
        unset($fo);
        // print the file contents
        var_dump(file_get_contents($file));
        //delete file
        unlink($file);
    }
    //end of mode loop
}
// end of foreach
echo "Done\n";
<?php

$file = __DIR__ . '/SplFileObject_fputcsv.csv';
$fo = new SplFileObject($file, 'w');
$list = array(0 => 'aaa,bbb', 1 => 'aaa,"bbb"', 2 => '"aaa","bbb"', 3 => 'aaa,bbb', 4 => '"aaa",bbb', 5 => '"aaa",   "bbb"', 6 => ',', 7 => 'aaa,', 8 => ',"aaa"', 9 => '"",""', 10 => '"""""",', 11 => '""""",aaa', 12 => 'aaa,bbb   ', 13 => 'aaa,"bbb   "', 14 => 'aaa"aaa","bbb"bbb', 15 => 'aaa"aaa""",bbb', 16 => 'aaa,"\\"bbb,ccc', 17 => 'aaa"\\"a","bbb"', 18 => '"\\"","aaa"', 19 => '"\\""",aaa');
foreach ($list as $v) {
    $fo->fputcsv(explode(',', $v));
}
unset($fo);
$res = file($file);
foreach ($res as &$val) {
    $val = substr($val, 0, -1);
}
echo '$list = ';
var_export($res);
echo ";\n";
$fp = fopen($file, "r");
$res = array();
while ($l = fgetcsv($fp)) {
    $res[] = join(',', $l);
}
fclose($fp);
echo '$list = ';
var_export($res);
echo ";\n";
?>
===DONE===
<?php

$fo = new SplFileObject(__DIR__ . '/SplFileObject_fputcsv2.csv', 'w');
echo "*** Testing error conditions ***\n";
// zero argument
echo "-- Testing fputcsv() with zero argument --\n";
var_dump($fo->fputcsv());
// more than expected no. of args
echo "-- Testing fputcsv() with more than expected number of arguments --\n";
$fields = array("fld1", "fld2");
$delim = ";";
$enclosure = "\"";
$escape = "\\";
var_dump($fo->fputcsv($fields, $delim, $enclosure, $escape, $fo));
echo "Done\n";