本文整理汇总了PHP中str_getcsv函数的典型用法代码示例。如果您正苦于以下问题:PHP str_getcsv函数的具体用法?PHP str_getcsv怎么用?PHP str_getcsv使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了str_getcsv函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: csv_unserialize
/**
* Unserializes a CSV string to an array
*
* @param string $src
* @param array $opts
*
* @return array
*/
function csv_unserialize(string $src, array $opts = []) : array
{
$opts = array_replace(CSV_OPTS, $opts);
if (!($rows = str_getcsv($src, "\n"))) {
return [];
}
$data = [];
$keys = [];
if ($opts['first_row_as_keys']) {
$keys = $rows[0];
unset($rows[0]);
} elseif ($opts['keys'] && is_array($opts['keys'])) {
$keys = $opts['keys'];
}
$k = count($keys);
$skel = array_fill(0, $k, null);
foreach ($rows as $row => $item) {
$item = str_getcsv($item, $opts['delimiter'], $opts['enclosure'], $opts['escape']);
if ($opts['single_item']) {
$data[$item[0]] = $item[1];
} elseif ($keys) {
$item = $k >= count($item) ? array_replace($skel, $item) : array_slice($item, 0, $k);
$data[] = array_combine($keys, $item);
} else {
$data[] = $item;
}
}
return $data;
}
示例2: getActiveStocks
public function getActiveStocks()
{
/*
$url = 'http://bsx.jlparry.com/data/stocks';
$data = array( );
// use key 'http' even if you send the request to https://...
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false);
if ($result == FALSE) { /* Handle error }
$actStocks = array();
$actStocks =str_getcsv ( string $result [, string $delimiter = "," [, string $enclosure = '"' [, string $escape = "\\" ]]] )
//$gameState['stockinfo']=
return $actStocks;
//var_dump($result);
*/
$url = DATAPATH . 'data/' . 'stocks';
$csv = file_get_contents($url);
$csvData = file_get_contents($csv);
$lines = explode(PHP_EOL, $csvData);
$array = array();
foreach ($lines as $line) {
$array[] = str_getcsv($line);
}
print_r($array);
}
示例3: LoadMatrix
/**
* Load Matrix.
* Load csv file containing the Database translation information.
*
* @param string $filePath.
*
* @return array.
*/
public function LoadMatrix($filePath = null)
{
// Default file path
if (empty($filePath)) {
$filePath = dirname(__FILE__) . DIRECTORY_SEPARATOR . self::MARTIX_FILE_NAME;
}
// Ensure the path is readable
if (!is_readable($filePath)) {
throw new Exception('DB Roller: File not readable: ' . $filePath);
}
// Get the File Contents
$dataString = file_get_contents($filePath);
if (empty($dataString)) {
throw new Exception('DB Roller: File was empty or failed to load: ' . $filePath);
}
// Normalise Linebreaks
//$dataString = preg_replace('/\r\n|\r|\n/', PHP_EOL, $dataString);
$dataString = str_replace(array("\r\n", "\r", "\n"), PHP_EOL, $dataString);
// Create Matrix as a Multi-Dim Array
$this->matrix = array_map(function ($row) {
return array_map(function ($col) {
return strtoupper(trim($col));
}, str_getcsv($row));
}, explode(PHP_EOL, $dataString));
// Return the Matrix
return $this->matrix;
}
示例4: smarty_function_mtarraymerge
function smarty_function_mtarraymerge($args, &$ctx)
{
if (isset($args['name'])) {
$names = $args['name'];
}
if (isset($args['set'])) {
$set = $args['set'];
}
if (!$names) {
return '';
}
if (!is_array($names)) {
if (strpos($names, ':') !== FALSE) {
$names = str_getcsv($names, ':');
$_names = array();
foreach ($names as $name) {
array_push($_names, $name);
}
$names = $_names;
}
}
$new_var = array();
foreach ($names as $name) {
$var = $ctx->__stash['vars'][$name];
if (!$var) {
$var = $ctx->__stash['vars'][strtolower($name)];
}
$new_var = array_merge($new_var, $var);
}
$ctx->__stash['vars'][$set] = $new_var;
$ctx->__stash['vars'][strtolower($set)] = $new_var;
}
示例5: csvToContactCollection
protected function csvToContactCollection($input)
{
$input = str_getcsv($input, "\n");
//parse the rows
$headings = array_shift($input);
$headings = str_getcsv($headings, ',');
$contacts = array();
while ($row = array_shift($input)) {
$row = str_getcsv($row, ",");
//parse the items in rows
$item = array();
$reason = $row[0];
$email = $row[1];
$contact = new ContactWithReason(array('email' => $email, 'reason' => $reason));
foreach ($row as $idx => $value) {
if ($idx < 2) {
continue;
}
$contact->setDataField(strtoupper($headings[$idx]), $value);
}
$contacts[] = $contact;
}
$collection = new ContactCollection($contacts);
return $collection;
}
示例6: find
/**
* {@inheritdoc}
*/
public function find($ip, $url, $limit, $method, $start = null, $end = null)
{
$file = $this->getIndexFilename();
if (!file_exists($file)) {
return array();
}
$file = fopen($file, 'r');
fseek($file, 0, SEEK_END);
$result = array();
while (count($result) < $limit && ($line = $this->readLineFromFile($file))) {
$values = str_getcsv($line);
list($csvToken, $csvIp, $csvMethod, $csvUrl, $csvTime, $csvParent) = $values;
$csvStatusCode = isset($values[6]) ? $values[6] : null;
$csvTime = (int) $csvTime;
if ($ip && false === strpos($csvIp, $ip) || $url && false === strpos($csvUrl, $url) || $method && false === strpos($csvMethod, $method)) {
continue;
}
if (!empty($start) && $csvTime < $start) {
continue;
}
if (!empty($end) && $csvTime > $end) {
continue;
}
$result[$csvToken] = array('token' => $csvToken, 'ip' => $csvIp, 'method' => $csvMethod, 'url' => $csvUrl, 'time' => $csvTime, 'parent' => $csvParent, 'status_code' => $csvStatusCode);
}
fclose($file);
return array_values($result);
}
示例7: checkFileContent
protected static function checkFileContent()
{
$fileContent = file_get_contents(static::$tmpFilepath);
// check encoding and convert to utf-8 when necessary
$detectedEncoding = mb_detect_encoding($fileContent, 'UTF-8, ISO-8859-1, WINDOWS-1252', true);
if ($detectedEncoding) {
if ($detectedEncoding !== 'UTF-8') {
$fileContent = iconv($detectedEncoding, 'UTF-8', $fileContent);
}
} else {
echo 'Zeichensatz der CSV-Date stimmt nicht. Der sollte UTF-8 oder ISO-8856-1 sein.';
return false;
}
//prepare data array
$tmpData = str_getcsv($fileContent, PHP_EOL);
array_shift($tmpData);
$preparedData = [];
$data = array_map(function ($row) use(&$preparedData) {
$tmpDataArray = str_getcsv($row, ';');
$tmpKey = trim($tmpDataArray[0]);
array_shift($tmpDataArray);
$preparedData[$tmpKey] = $tmpDataArray;
}, $tmpData);
// generate json
$jsonContent = json_encode($preparedData, JSON_HEX_TAG | JSON_HEX_AMP);
self::$jsonContent = $jsonContent;
return true;
}
示例8: smarty_function_mtdeletevars
function smarty_function_mtdeletevars($args, &$ctx)
{
if (isset($args['name'])) {
$name = $args['name'];
}
if (!$name) {
return '';
}
$names = array();
if (!is_array($name)) {
if (strpos($name, ':') !== FALSE) {
$_names = str_getcsv($name, ':');
$__names = array();
foreach ($_names as $_name) {
if (strpos($_name, 'Array.') === 0) {
$_name = str_replace('Array.', '', $_name);
$_name = $ctx->__stash['vars'][$_name];
}
array_push($__names, $_name);
}
$names = $__names;
} else {
if (strpos($name, ' ') !== FALSE) {
$names = explode(' ', $name);
} else {
$names = array($name);
}
}
}
foreach ($names as $name) {
$name = trim($name);
unset($ctx->__stash['vars'][$name]);
}
}
示例9: main
public function main()
{
// load CURL class
require dirname(__FILE__) . '/lib/CURL.php';
// iterator over hashes
foreach ($this->hashes as $index => $hash) {
// check if csv line data
$fields = str_getcsv($hash, ';');
if (count($fields) > 1) {
$this->out('Trying hash: ' . implode(', ', $fields) . ' … ', false);
$hash = $fields[count($fields) - 1];
} else {
$this->out('Trying hash: ' . $hash . ' … ', false);
}
// use curl to send request to md5crack
$CURL = new CURL('http://md5crack.com/crackmd5.php', array(CURLOPT_POSTFIELDS => array('term' => $hash, 'crackbtn' => true)));
// search for result string
if (preg_match('@Found:\\s+md5\\("(?P<source>.+)"\\)\\s=\\s+([a-z0-9]+)@mi', $CURL->read(), $found)) {
$this->out($found['source']);
} else {
$this->out('not found');
}
}
$this->quit('done!');
}
示例10: localSqlSync
public function localSqlSync()
{
$dump_dir = UNISH_SANDBOX . "/dump-dir";
if (!is_dir($dump_dir)) {
mkdir($dump_dir);
}
// Create a user in the staging site
$name = 'joe.user';
$mail = "joe.user@myhome.com";
$options = array('root' => $this->webroot(), 'uri' => 'stage', 'yes' => NULL);
$this->drush('user-create', array($name), $options + array('password' => 'password', 'mail' => $mail));
// Copy stage to dev with --sanitize
$sync_options = array('sanitize' => NULL, 'yes' => NULL, 'dump-dir' => $dump_dir);
$this->drush('sql-sync', array('@stage', '@dev'), $sync_options);
// Confirm that the sample user has the correct email address on the staging site
$this->drush('user-information', array($name), $options + array('pipe' => NULL));
$output = $this->getOutput();
$row = str_getcsv($output);
$uid = $row[1];
$this->assertEquals($mail, $row[2], 'email address is unchanged on source site.');
$this->assertEquals($name, $row[0]);
$options = array('root' => $this->webroot(), 'uri' => 'dev', 'yes' => NULL);
// Confirm that the sample user's email address has been sanitized on the dev site
$this->drush('user-information', array($name), $options + array('pipe' => NULL));
$output = $this->getOutput();
$row = str_getcsv($output);
$uid = $row[1];
$this->assertEquals("user+{$uid}@localhost", $row[2], 'email address was sanitized on destination site.');
$this->assertEquals($name, $row[0]);
}
示例11: getWeatherData
function getWeatherData($strURL, $strCacheFile, $intLimitHours, &$strGeographicLocation)
{
if (!file_exists($strCacheFile) || filemtime($strCacheFile) + 60 * 60 * $intLimitHours < time()) {
$arrCacheData = file($strURL);
if (!$arrCacheData) {
die('Problem Retrieving NOAA Data! Please try your request again.');
}
$arrGeographicLocation = explode('"', $arrCacheData[1], 3);
$strGeographicLocation = str_replace('"', '', $arrGeographicLocation[1]);
$arrCacheData = array_filter($arrCacheData, "removeWeatherXMLCruft");
$arrCacheData = array_merge($arrCacheData);
$fdCacheFile = fopen($strCacheFile, "w");
fputs($fdCacheFile, $strGeographicLocation . "\n");
for ($i = 0; $i < sizeof($arrCacheData); $i++) {
fputs($fdCacheFile, $arrCacheData[$i]);
}
fclose($fdCacheFile);
}
$arrCacheData = array();
$fdCacheFile = fopen($strCacheFile, "r");
$strGeographicLocation = stream_get_line($fdCacheFile, 4096, "\n");
while (!feof($fdCacheFile)) {
$arrCacheData[] = stream_get_line($fdCacheFile, 4096, "\n");
}
fclose($fdCacheFile);
$strWeatherData = implode("\r\n", $arrCacheData);
$strWeatherData = strip_tags(str_replace(array(',', "\r\n"), array('', ','), $strWeatherData));
$arrCacheData = str_getcsv($strWeatherData);
return array_chunk($arrCacheData, 3);
}
示例12: upload_graduate_attributes
/**
* Upload graduate attributes and insert all entries to graduateattributes table.
* @param object $mform form definition
* @return void
*/
private function upload_graduate_attributes($mform)
{
global $DB, $CFG, $USER;
$gradatt_was_uploaded = $mform->getSubmitValue('upload_gradatt');
if ($gradatt_was_uploaded) {
$files = $this->get_draft_files('temp_gradatt');
if (!empty($files)) {
$file = reset($files);
$content = $file->get_content();
$all_rows = explode("\n", $content);
$current_parent = 0;
foreach ($all_rows as $row) {
$parsed = str_getcsv($row);
if (!is_null($parsed[0])) {
// $parsed[0] is not empty, then it is the main level
if ($parsed[0] != '') {
$parent = new stdClass();
$parent->attribute = $parsed[1];
$insert_gradatt = $DB->insert_record('graduateattributes', $parent, true, false);
$current_parent = $insert_gradatt;
$node = new stdClass();
$node->attribute = $parsed[3];
$node->node = $current_parent;
$insert_sub_gradatt = $DB->insert_record('graduateattributes', $node, true, false);
} else {
$node = new stdClass();
$node->attribute = $parsed[3];
$node->node = $current_parent;
$insert_sub_gradatt = $DB->insert_record('graduateattributes', $node, true, false);
}
}
}
}
}
}
示例13: parse
/**
* @param string $input
* @param string $delimiter
* @param array $options
* @throws ParseException
* @return array
*/
public function parse($input, $delimiter = ';', array $options = array())
{
$default_options = array('encoding_source' => 'UTF-8', 'encoding_target' => 'UTF-8');
$options = array_merge($default_options, $options);
try {
$input = iconv($options['encoding_source'], $options['encoding_target'], $input);
} catch (\Exception $e) {
throw new ParseException('The file might not be a CSV file after all.');
}
if (preg_split('/$\\R?^/m', $input) > explode("\r\n", $input)) {
$lines = preg_split('/$\\R?^/m', $input);
} else {
$lines = explode("\r\n", $input);
}
$lines = array_map('trim', $lines);
$header = trim($lines[0]);
unset($lines[0]);
$keys = explode($delimiter, $header);
$result = array();
foreach ($lines as $line_no => $line) {
if (0 === strlen($line)) {
continue;
}
$values = str_getcsv($line, $delimiter);
try {
if (is_array($keys) && is_array($values) && count($keys) !== count($values)) {
throw new \DomainException();
}
$result[] = array_combine($keys, $values);
} catch (\DomainException $e) {
throw new ParseException(sprintf('The CSV-file seems to be damaged. Found %d header columns but %d data columns on line %d.', count($keys), count($values), $line_no));
}
}
return $result;
}
示例14: convertToXML
/**
* Given a CSV file, generate a resulting XML tree
*
* @param string $data
* @return string
*/
public static function convertToXML($data)
{
$headers = array();
// Get CSV settings
$settings = array('csv-delimiter' => ',', 'csv-enclosure' => '"', 'csv-escape' => '\\');
$settings = array_merge($settings, (array) Symphony::Configuration()->get('remote_datasource'));
// DOMDocument
$doc = new DOMDocument('1.0', 'utf-8');
$doc->formatOutput = true;
$root = $doc->createElement('data');
$doc->appendChild($root);
foreach (str_getcsv($data, PHP_EOL) as $i => $row) {
if (empty($row)) {
continue;
}
if ($i == 0) {
foreach (str_getcsv($row, $settings['csv-delimiter'], $settings['csv-enclosure'], $settings['csv-escape']) as $i => $head) {
if (class_exists('Lang')) {
$head = Lang::createHandle($head);
}
$headers[] = $head;
}
} else {
self::addRow($doc, $root, str_getcsv($row, $settings['csv-delimiter'], $settings['csv-enclosure'], $settings['csv-escape']), $headers);
}
}
$output = $doc->saveXML($doc->documentElement);
return trim($output);
}
示例15: __construct
public function __construct($harvester, $name, $parameters)
{
parent::__construct($harvester, $name, $parameters);
// Load in the corrections from the datafile.
if (array_key_exists('datafile', $parameters)) {
$datafile = $parameters['datafile'];
$datafile = $harvester->resolvePath($datafile);
if ($datafile) {
$datafile = file_get_contents($datafile);
$datafile_rows = str_getcsv($datafile, "\n");
foreach ($datafile_rows as $row) {
$row = str_getcsv($row, ";");
if (count($row) != 3) {
throw new \RuntimeException("Malformed datafile, all rows have to have exact 3 collumns, seperated by semicolons.");
}
$brokenProductionID = strval($row[0]);
$correctProductionID = strval($row[1]);
$assetID = strval($row[2]);
if (is_numeric($correctProductionID) && is_numeric($assetID)) {
$this->_translationsByBrokenProductionID[$brokenProductionID] = $correctProductionID;
$this->_translationsByAssetID[$assetID] = $correctProductionID;
} else {
$harvester->debug("A line in the {$name} " . __CLASS__ . " datafile had non-nummeric values: It was skipped.");
}
}
} else {
throw new \Exception("The " . __CLASS__ . " has to have a datafile parameter that points to a datafile.");
}
} else {
throw new \Exception("The " . __CLASS__ . " has to have a datafile parameter.");
}
}