当前位置: 首页>>代码示例>>PHP>>正文


PHP fgetcsv函数代码示例

本文整理汇总了PHP中fgetcsv函数的典型用法代码示例。如果您正苦于以下问题:PHP fgetcsv函数的具体用法?PHP fgetcsv怎么用?PHP fgetcsv使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了fgetcsv函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。

示例1: lookup

/**
 * Returns a stock by symbol (case-insensitively) else false if not found.
 */
function lookup($symbol)
{
    // reject symbols that start with ^
    if (preg_match("/^\\^/", $symbol)) {
        return false;
    }
    // reject symbols that contain commas
    if (preg_match("/,/", $symbol)) {
        return false;
    }
    // open connection to Yahoo
    $handle = @fopen("http://download.finance.yahoo.com/d/quotes.csv?f=snl1&s={$symbol}", "r");
    if ($handle === false) {
        // trigger (big, orange) error
        trigger_error("Could not connect to Yahoo!", E_USER_ERROR);
        exit;
    }
    // download first line of CSV file
    $data = fgetcsv($handle);
    if ($data === false || count($data) == 1) {
        return false;
    }
    // close connection to Yahoo
    fclose($handle);
    // ensure symbol was found
    if ($data[2] === "0.00") {
        return false;
    }
    // return stock as an associative array
    return ["symbol" => $data[0], "name" => $data[1], "price" => $data[2]];
}
开发者ID:ilyarudyak,项目名称:cs50_h,代码行数:34,代码来源:functions.php

示例2: rechazadas

 public function rechazadas($q)
 {
     $url = 'https://docs.google.com/spreadsheets/d/1qxVqiUQNXyl26pY7f16OP5oWSCbp4wmykwgAJi762bc/pub?output=csv';
     $headers = false;
     $list = array();
     // open file for reading
     if (($handle = fopen($url, "r")) !== FALSE) {
         while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
             if ($headers) {
                 $totalrows = count($data) - 1;
                 $temp = array();
                 for ($row = 0; $row <= $totalrows; $row++) {
                     $temp[$headers[$row]] = $data[$row];
                 }
                 $list[] = $temp;
             } else {
                 $headers = $data;
             }
         }
         fclose($handle);
     }
     $collection = collect($list)->reject(function ($r) use($q) {
         return !(strpos(strtolower($r['materia_resumen']), strtolower($q)) > -1);
     });
     $resp = array('q' => $q, 'list' => $collection);
     return response()->json($resp);
 }
开发者ID:fmultitudes,项目名称:lobby-tools,代码行数:27,代码来源:TemasController.php

示例3: _getSubscriberCSV

 function _getSubscriberCSV()
 {
     $keys = array();
     $subscribers = array();
     $subscriber = array();
     jimport('joomla.filesystem.file');
     $allowedExts = array('csv');
     $csvFile = $_FILES['csv_subscribers'];
     $csvFileName = $csvFile['tmp_name'];
     $fileName = $csvFile['name'];
     $fileExt = strtolower(JFile::getExt($fileName));
     if (in_array($fileExt, $allowedExts)) {
         $line = 0;
         $fp = fopen($csvFileName, 'r');
         while (($cells = fgetcsv($fp)) !== FALSE) {
             if ($line == 0) {
                 foreach ($cells as $key) {
                     $keys[] = $key;
                 }
                 $line++;
             } else {
                 $i = 0;
                 foreach ($cells as $cell) {
                     $subscriber[$keys[$i]] = $cell;
                     $i++;
                 }
                 $subscribers[] = $subscriber;
             }
         }
         fclose($fp);
         return $subscribers;
     }
 }
开发者ID:vstorm83,项目名称:propertease,代码行数:33,代码来源:import.php

示例4: load

 /**
  * load the locale
  *
  * @access public
  * @param  string $code
  */
 public static function load($code)
 {
     if (self::$_directory === null) {
         self::$_directory = dirname(dirname(__FILE__)) . '/locale/';
     }
     // must be in lower case
     $code = strtolower($code);
     // must be [a-z-0-9]
     if (!preg_match('/^([a-z0-9]+)$/isU', $code)) {
         throw new HTML2PDF_exception(0, 'invalid language code [' . self::$_code . ']');
     }
     // save the code
     self::$_code = $code;
     // get the name of the locale file
     $file = self::$_directory . self::$_code . '.csv';
     // the file must exist
     if (!is_file($file)) {
         throw new HTML2PDF_exception(0, 'language code [' . self::$_code . '] unknown. You can create the translation file [' . $file . '] and send it to the webmaster of html2pdf in order to integrate it into a future release');
     }
     // load the file
     self::$_list = array();
     $handle = fopen($file, 'r');
     while (!feof($handle)) {
         $line = fgetcsv($handle);
         if (count($line) != 2) {
             continue;
         }
         self::$_list[trim($line[0])] = trim($line[1]);
     }
     fclose($handle);
 }
开发者ID:roger-jb,项目名称:edeip,代码行数:37,代码来源:locale.class.php

示例5: readTempSDB

function readTempSDB()
{
    $delimiter = ',';
    $header = NULL;
    $d = array();
    if (($handle = fopen("plugins/TEMP/db.sdb", 'r')) !== FALSE) {
        while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE) {
            if (!$header) {
                $header = $row;
            } else {
                $d[] = array_combine($header, $row);
            }
        }
        fclose($handle);
    }
    foreach ($d as $data) {
        foreach ($data as $row) {
            $r = explode(";", $row);
            $data1 = $r[0];
            $data2 = $r[1];
            $return[$data1] = $data2;
        }
    }
    return $return;
}
开发者ID:vantezzen,项目名称:synchro,代码行数:25,代码来源:dlpluginfromzip.php

示例6: execute

 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $file = $input->getArgument('file');
     if (!file_exists($file) || !($fh = fopen($file, 'r'))) {
         $output->writeln('<error>Can\'t read data from file</error>');
         return null;
     }
     //собираем из файла популярные города
     $popular = [];
     while (($data = fgetcsv($fh)) !== false) {
         //без идентификатора не обрабатываем
         if (empty($data[0])) {
             continue;
         }
         //пробуем найти указанный город
         $popular[] = $data[0];
     }
     fclose($fh);
     $popular = array_unique($popular);
     $id = 0;
     //перебираем все города
     while ($list = \bxpimple\Locator::$item->get('cityFinder')->mergeFilterWith(['>ID' => $id])->setOrder(['id' => 'asc'])->setLimit(50)->all()) {
         foreach ($list as $city) {
             $pop = in_array($city->name->value, $popular);
             $city->property_city_is_popular->value = $pop ? '1' : '';
             $city->save();
             $output->writeln('<info>Proceed city ' . $city->name->value . '. City is ' . ($pop ? 'popular' : 'not popular') . '</info>');
             $id = $city->id->value;
         }
     }
 }
开发者ID:bfday,项目名称:1c_bitrix_initial_repo,代码行数:31,代码来源:ImportPopularCities.php

示例7: _loadTranslationData

 /**
  * Load translation data
  *
  * @param  string|array  $filename  Filename and full path to the translation source
  * @param  string        $locale    Locale/Language to add data for, identical with locale identifier,
  *                                  see Zend_Locale for more information
  * @param  array         $option    OPTIONAL Options to use
  * @return array
  */
 protected function _loadTranslationData($filename, $locale, array $options = array())
 {
     $this->_data = array();
     $options = $options + $this->_options;
     $this->_file = @fopen($filename, 'rb');
     if (!$this->_file) {
         // require_once 'Zend/Translate/Exception.php';
         throw new Zend_Translate_Exception('Error opening translation file \'' . $filename . '\'.');
     }
     while (($data = fgetcsv($this->_file, $options['length'], $options['delimiter'], $options['enclosure'])) !== false) {
         if (substr($data[0], 0, 1) === '#') {
             continue;
         }
         if (!isset($data[1])) {
             continue;
         }
         if (count($data) == 2) {
             $this->_data[$locale][$data[0]] = $data[1];
         } else {
             $singular = array_shift($data);
             $this->_data[$locale][$singular] = $data;
         }
     }
     return $this->_data;
 }
开发者ID:openbizx,项目名称:openbizx-cubix,代码行数:34,代码来源:Csv.php

示例8: fgethandle

 function fgethandle(&$handle, &$contents)
 {
     $line = 0;
     $contents = array();
     $is_utf8 = true;
     while ($row = fgetcsv($handle)) {
         foreach ($row as $num => $col) {
             if ($line == 0 && $num == 0) {
                 // 判断下文档的字符集.
                 if (!$this->charset->is_utf8($col)) {
                     $is_utf8 = false;
                 } else {
                     if ($col_tmp = $this->charset->replace_utf8bom($col)) {
                         // 替换两个双引号
                         $col = substr($col_tmp, 1, -1);
                     }
                 }
             }
             if (!$is_utf8) {
                 $contents[$line][$num] = $this->charset->local2utf((string) $col);
             } else {
                 $contents[$line][$num] = (string) $col;
             }
         }
         $line++;
     }
 }
开发者ID:453111208,项目名称:bbc,代码行数:27,代码来源:csv.php

示例9: test5Transactions

 public function test5Transactions()
 {
     $inputFile = fopen('php://memory', 'w+');
     $outputFile = fopen('php://memory', 'w+');
     $csv = array(array('AMOUNT' => 100, 'OPERATIONTYPE' => 'payment', 'CARDCODE' => '5555556778250000', 'CARDVALIDITYDATE' => $this->tools->getFutureValidityDate(), 'CARDCVV' => '123', 'CARDFULLNAME' => 'John Doe', 'ORDERID' => 'order_' . time(), 'CLIENTIDENT' => 'john.doe', 'CLIENTEMAIL' => 'john.doe42', 'CLIENTEMAIL' => 'john.doe@mail.com', 'DESCRIPTION' => 'Test', 'CLIENTUSERAGENT' => 'firefox', 'CLIENTIP' => '1.2.3.4', 'VERSION' => '2.0'), array('AMOUNT' => 100, 'OPERATIONTYPE' => 'payment', 'CARDCODE' => '5555554530114002', 'CARDVALIDITYDATE' => $this->tools->getFutureValidityDate(), 'CARDCVV' => '123', 'CARDFULLNAME' => 'John Doe', 'ORDERID' => 'order_' . time(), 'CLIENTIDENT' => 'john.doe', 'CLIENTEMAIL' => 'john.doe42', 'CLIENTEMAIL' => 'john.doe@mail.com', 'DESCRIPTION' => 'Test', 'CLIENTUSERAGENT' => 'firefox', 'CLIENTIP' => '1.2.3.4', 'VERSION' => '2.0'), array('AMOUNT' => 100, 'OPERATIONTYPE' => 'payment', 'CARDCODE' => '', 'CARDVALIDITYDATE' => $this->tools->getFutureValidityDate(), 'CARDCVV' => '123', 'CARDFULLNAME' => 'John Doe', 'ORDERID' => 'order_' . time(), 'CLIENTIDENT' => 'john.doe', 'CLIENTEMAIL' => 'john.doe42', 'CLIENTEMAIL' => 'john.doe@mail.com', 'DESCRIPTION' => 'Test', 'CLIENTUSERAGENT' => 'firefox', 'CLIENTIP' => '1.2.3.4', 'VERSION' => '2.0'), array('AMOUNT' => 100, 'OPERATIONTYPE' => 'payment', 'CARDCODE' => '5555556778250000', 'CARDVALIDITYDATE' => $this->tools->getFutureValidityDate(), 'CARDCVV' => '123', 'CARDFULLNAME' => 'John Doe', 'ORDERID' => 'order_' . time(), 'CLIENTIDENT' => 'john.doe', 'CLIENTEMAIL' => 'john.doe42', 'CLIENTEMAIL' => 'john.doe@mail.com', 'DESCRIPTION' => 'Test', 'CLIENTUSERAGENT' => 'firefox', 'CLIENTIP' => '1.2.3.4', 'VERSION' => '2.0'));
     fputcsv($inputFile, array_keys(current($csv)), ';');
     foreach ($csv as $line) {
         fputcsv($inputFile, $line, ';');
     }
     rewind($inputFile);
     $batchApi = Be2bill_Api_ClientBuilder::buildSandboxBatchClient($this->getIdentifier(), $this->getPassword());
     $batchApi->setInputFile($inputFile);
     $batchApi->attach(new Be2bill_Api_Batch_Observer_Debug());
     $batchApi->attach(new Be2bill_Api_Batch_Observer_FileReport($outputFile));
     $batchApi->run();
     rewind($outputFile);
     $i = 0;
     while (!feof($outputFile)) {
         $line = fgetcsv($outputFile, null, ';');
         // HACK for phpunit version >= 5.2
         if ($line) {
             $i++;
         }
     }
     $this->expectOutputRegex('/Line 1.+\\nLine 2.+\\nLine 3.+\\nLine 4.+\\n/');
     $this->assertEquals(5, $i);
 }
开发者ID:be2bill,项目名称:php-merchant-api,代码行数:27,代码来源:BatchClientTest.php

示例10: get_csv_header_fields

 function get_csv_header_fields()
 {
     $this->arr_csv_columns = array();
     $fpointer = fopen($this->file_name, "r");
     if ($fpointer) {
         $arr = fgetcsv($fpointer, 10 * 1024, $this->field_separate_char);
         if (is_array($arr) && !empty($arr)) {
             if ($this->use_csv_header) {
                 foreach ($arr as $val) {
                     if (trim($val) != "") {
                         $this->arr_csv_columns[] = $val;
                     }
                 }
             } else {
                 $i = 1;
                 foreach ($arr as $val) {
                     if (trim($val) != "") {
                         $this->arr_csv_columns[] = "column" . $i++;
                     }
                 }
             }
         }
         unset($arr);
         fclose($fpointer);
     } else {
         $this->error = "file cannot be opened: " . ("" == $this->file_name ? "[empty]" : @mysql_escape_string($this->file_name));
     }
     return $this->arr_csv_columns;
 }
开发者ID:ViShNuPrAtap,项目名称:lss,代码行数:29,代码来源:Quick_CSV_import.php

示例11: parseAccountReport

 /**
  * @param (String) $filePath
  * @return (Array) $result
  **/
 private function parseAccountReport($filePath)
 {
     $i = 0;
     if (($handle = fopen($filePath, "r")) !== FALSE) {
         while (($data = fgetcsv($handle, 0, ",")) !== FALSE) {
             if ($i >= 2) {
                 //On saute les 2 première lignes qui sont "nom du rapport" et nom des champs
                 //Si le compte à aucune datas, on corrige le bug du rapport
                 for ($i = 0; $i < count($data); $i++) {
                     if ($data[$i] == "Total") {
                         $data[$i] = 0;
                     }
                 }
                 $result[] = $data;
             }
             $i++;
         }
         fclose($handle);
     }
     if (count($result) > 1) {
         array_pop($result);
     }
     // On supprime la ligne Total
     return $result;
 }
开发者ID:AlexandreAWE,项目名称:node-adwords-api-phplib,代码行数:29,代码来源:ReportDefinitionService.php

示例12: submitForm

 public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $form_state)
 {
     // Check to make sure that the file was uploaded to the server properly
     $userInputValues = $form_state->getUserInput();
     $uri = db_select('file_managed', 'f')->condition('f.fid', $userInputValues['import']['fids'], '=')->fields('f', array('uri'))->execute()->fetchField();
     if (!empty($uri)) {
         if (file_exists(\Drupal::service("file_system")->realpath($uri))) {
             // Open the csv
             $handle = fopen(\Drupal::service("file_system")->realpath($uri), "r");
             // Go through each row in the csv and run a function on it. In this case we are parsing by '|' (pipe) characters.
             // If you want commas are any other character, replace the pipe with it.
             while (($data = fgetcsv($handle, 0, ',', '"')) !== FALSE) {
                 $operations[] = ['csvimport_import_batch_processing', [$data]];
             }
             // Once everything is gathered and ready to be processed... well... process it!
             $batch = ['title' => t('Importing CSV...'), 'operations' => $operations, 'finished' => $this->csvimport_import_finished(), 'error_message' => t('The installation has encountered an error.'), 'progress_message' => t('Imported @current of @total products.')];
             batch_set($batch);
             fclose($handle);
         } else {
             drupal_set_message(t('Not able to find file path.'), 'error');
         }
     } else {
         drupal_set_message(t('There was an error uploading your file. Please contact a System administator.'), 'error');
     }
 }
开发者ID:atif-shaikh,项目名称:DCX-Profile,代码行数:25,代码来源:CsvimportImportForm.php

示例13: handle

 /**
  * Execute the console command.
  *
  * @return mixed
  */
 public function handle()
 {
     /** @var Keytype $keytype */
     $keytype = Keytype::create(['name' => 'countries', 'description' => 'ISO 3166 Country Codes', 'created_by' => 'loader', 'updated_by' => 'loader']);
     $handle = fopen($this->filename, 'r');
     // Get this in advance by calling wc -l $file
     $count = 246;
     $bar = $this->output->createProgressBar($count);
     while ($data = fgetcsv($handle)) {
         try {
             list($country_code, $country_name) = $data;
         } catch (\Exception $e) {
             continue;
         }
         // progress advance
         $bar->advance();
         // Skip the first line
         if ($country_code == "country_code") {
             continue;
         }
         // Create the entry
         Keyvalue::create(['keytype_id' => $keytype->id, 'keyvalue' => $country_code, 'keyname' => $country_name, 'created_by' => 'loader', 'updated_by' => 'loader']);
     }
     fclose($handle);
     $bar->finish();
     $this->output->writeln('Finished');
 }
开发者ID:delatbabel,项目名称:keylists,代码行数:32,代码来源:LoadISO3166Countries.php

示例14: initialize

 public function initialize($params)
 {
     $this->_mapping = array();
     $dlist = glob(dirname(__FILE__) . "/mappings/default/*.csv");
     if ($dlist == false) {
         $dlist = array();
         $this->log("No default mapping found", "warning");
     }
     $slist = glob(dirname(__FILE__) . "/mappings/*.csv");
     if ($slist == false) {
         $slist = array();
         $this->log("No custom mapping found", "startup");
     }
     $flist = array_merge($dlist, $slist);
     foreach ($flist as $fname) {
         $idx = basename($fname);
         if (!isset($this->_mapping[$idx])) {
             $this->_mapping[$idx] = array("DIRECT" => array(), "RE" => array());
         }
         $mf = fopen("{$fname}", "r");
         while (($data = fgetcsv($mf, 1000, ",")) !== false) {
             if (substr($data[0], 0, 4) == "_RE:") {
                 $target = "RE";
                 $key = substr($data[0], 4);
             } else {
                 $target = "DIRECT";
                 $key = $data[0];
             }
             $this->_mapping[$idx][$target][$key] = $data[1];
         }
     }
 }
开发者ID:bjoern-tantau,项目名称:magmi-git,代码行数:32,代码来源:02_genericmapper.php

示例15: injectPhoneProperties

 /**
  * Dissect country code from phone number.
  *
  * @param  Phone                    $phone
  * @return $this
  * @throws InvalidArgumentException
  * @throws RuntimeException
  */
 public function injectPhoneProperties(Phone $phone)
 {
     if (!file_exists($this->getCountriesPath()) || !is_readable($this->getCountriesPath())) {
         throw new RuntimeException("File doesn't exists or isn't readable.");
     }
     if (($handle = fopen($this->getCountriesPath(), 'rb')) !== false) {
         while (($data = fgetcsv($handle, 1000)) !== false) {
             if (strpos($phone->getPhoneNumber(), $data[1]) === 0) {
                 // Return the first appearance.
                 fclose($handle);
                 $mcc = explode("|", $data[2]);
                 $mcc = $mcc[0];
                 //hook:
                 //fix country code for North America
                 if (substr($data[1], 0, 1) == "1") {
                     $data[1] = "1";
                 }
                 $phone->setCountry($data[0])->setCc($data[1])->setPhone(substr($phone->getPhoneNumber(), strlen($data[1]), strlen($phone->getPhoneNumber())))->setMcc($mcc)->setIso3166(isset($data[3]) ? $data[3] : null)->setIso639(isset($data[4]) ? $data[4] : null)->setMnc(isset($data[5]) ? $data[5] : null);
                 return $this;
             }
         }
         fclose($handle);
     }
     throw new InvalidArgumentException("Phone number not recognized");
 }
开发者ID:CarsonF,项目名称:WhatsApi,代码行数:33,代码来源:LocalizationService.php


注:本文中的fgetcsv函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。