function csvToJson($feed) { // Arrays we'll use later $keys = array(); $newArray = array(); // Do it $data = csvToArray($feed, ','); // Set number of elements (minus 1 because we shift off the first row) $count = count($data) - 1; //Use first row for names $labels = array_shift($data); foreach ($labels as $label) { $keys[] = $label; } // Add Ids, just in case we want them later $keys[] = 'id'; for ($i = 0; $i < $count; $i++) { $data[$i][] = $i; } // Bring it all together for ($j = 0; $j < $count; $j++) { $d = array_combine($keys, $data[$j]); $newArray[$j] = $d; } // Print it out as JSON return json_encode($newArray); }
public function __construct () { global $config; $this->setDB = new SetDB(); $this->artDB = new ArtDB($this->setDB); $this->cardDB = new CardDB($this->setDB, $this->artDB); $this->formatDB = new FormatDB($this->setDB, $this->cardDB); $this->fontSizeDB = new FontSizeDB($config['card.text.use.font.size.cache']); $this->titleToLandColors = csvToArray('data/titleToLandColors.csv'); $this->convertor = new Convertor(); }
/** * @param $url */ public function spreadsheet_json($url) { // header('Content-type: application/json'); // Set your CSV feed $feed = $url; // Arrays we'll use later $keys = array(); $newArray = array(); // Function to convert CSV into associative array function csvToArray($file, $delimiter) { if (($handle = fopen($file, 'r')) !== FALSE) { $i = 0; while (($lineArray = fgetcsv($handle, 4000, $delimiter, '"')) !== FALSE) { for ($j = 0; $j < count($lineArray); $j++) { $arr[$i][$j] = $lineArray[$j]; } $i++; } fclose($handle); } return $arr; } // Do it $data = csvToArray($feed, ','); // Set number of elements (minus 1 because we shift off the first row) $count = count($data) - 1; //Use first row for names $labels = array_shift($data); foreach ($labels as $label) { $keys[] = $label; } // Add Ids, just in case we want them later $keys[] = 'id'; for ($i = 0; $i < $count; $i++) { $data[$i][] = $i; } // Bring it all together for ($j = 0; $j < $count; $j++) { $d = array_combine($keys, $data[$j]); $newArray[$j] = $d; } // Print it out as JSON return json_encode($newArray, JSON_PRETTY_PRINT); }
function generate_json($doc) { $keys = array(); $geoData = array(); $data = csvToArray($doc, ','); // Set number of elements (minus 1 because we shift off the first row) $count = count($data) - 1; //Use first row for names $labels = array_shift($data); foreach ($labels as $label) { $keys[] = $label; } // Bring it all together for ($j = 0; $j < $count; $j++) { $d = array_combine($keys, $data[$j]); $geoData[$j] = $d; } return $geoData; }
function __construct() { $this->mtgoIdToTitle = csvToArray('data/mtgoIdToTitle.csv'); }
<?php header('Content-type: text/csv'); ini_set("auto_detect_line_endings", true); $FN_FILE = './data/CSV_Database_of_First_Names.csv'; $LN_FILE = './data/CSV_Database_of_Last_Names.csv'; $NUM_RECORDS = checkSet('recordcount', 100, false); $FN_Array = csvToArray($FN_FILE); $FN_Array_Sz = count($FN_Array); $LN_Array = csvToArray($LN_FILE); $LN_Array_Sz = count($LN_Array); $output = array(); //CSV Header $output[] = array('Mother', 'DOB', 'Father', 'DOB', 'Son', 'DOB', 'Daughter', 'DOB'); for ($i = 0; $i < $NUM_RECORDS; $i++) { $surName = rand(1, $LN_Array_Sz - 1); $output[] = array($FN_Array[rand(1, $FN_Array_Sz - 1)][0] . ' ' . $LN_Array[rand(1, $LN_Array_Sz - 1)][0], date("m/d/Y"), $FN_Array[rand(1, $FN_Array_Sz - 1)][0] . ' ' . $LN_Array[$surName][0], date("m/d/Y"), $FN_Array[rand(1, $FN_Array_Sz - 1)][0] . ' ' . $LN_Array[$surName][0], date("m/d/Y"), $FN_Array[rand(1, $FN_Array_Sz - 1)][0] . ' ' . $LN_Array[$surName][0], date("m/d/Y")); } str_putcsv($output); echo implode(PHP_EOL, $output); function str_putcsv(&$array) { $arraySz = count($array); for ($i = 0; $i < $arraySz; $i++) { $array[$i] = implode(',', $array[$i]); } return $array; } function csvToArray($fileName) { $array = array();
function csvToArray($file, $delimiter) { if (($handle = fopen($file, 'r')) !== FALSE) { $i = 0; while (($lineArray = fgetcsv($handle, 4000, $delimiter, '"')) !== FALSE) { for ($j = 0; $j < count($lineArray); $j++) { $arr[$i][$j] = $lineArray[$j]; //echo "Columna: $lineArray[$j]\n"; } $i++; } fclose($handle); } return $arr; } $data = csvToArray($feed, ';'); $dataNew = $data; //print_r($data); $count = count($data) - 1; //echo "count: $count"; array_shift($dataNew); array_shift($data); //print_r($labels); $keys = array("ref", "ordre", "nom", "desc", "thumb", "preu", "preuAntic", "tipus", "colors", "estoc"); //print_r($keys); for ($i = 0; $i < $count; $i++) { $dataNew[$i][9] = array(); //$dataNew[$i][9] = array($dataNew[$i][8] => array("talles" => array(), "imatges" => array())); array_splice($dataNew[$i], 10, 5); if ($dataNew[$i][0] == "") { array_splice($dataNew, $i, 1);
{ if (($handle = fopen($file, 'r')) !== FALSE) { $i = 0; while (($lineArray = fgetcsv($handle, 4000, $delimiter, '"')) !== FALSE) { for ($j = 0; $j < count($lineArray); $j++) { $arr[$i][$j] = $lineArray[$j]; } $i++; } fclose($handle); } return $arr; } // Do it $dataX = csvToArray($feedX, ','); $dataY = csvToArray($feedY, ','); // Set number of elements (minus 1 because we shift off the first row) $count = count($dataX) - 1; //Use first row for names $labels = array_shift($dataX); $labels = array_shift($dataY); foreach ($labels as $label) { $keys[] = $label; } // Bring it all together for ($j = 0; $j < $count; $j++) { $dX = array_combine($keys, $dataX[$j]); $arrayX[$j] = $dX; $dY = array_combine($keys, $dataY[$j]); $arrayY[$j] = $dY; }
// Generate CSV $CSVFileName = str_replace(".xlsx", ".csv", $filename); $CSVFileName = str_replace("excel/", "csv/", $CSVFileName); $excel = PHPExcel_IOFactory::load($filename); $writer = PHPExcel_IOFactory::createWriter($excel, 'CSV'); $writer->setDelimiter(","); //$writer->setEnclosure(""); //$writer->setLineEnding("\r\n"); $writer->setSheetIndex(0); $writer->save($CSVFileName); // Generate JSON $JSONFileName = str_replace(".csv", ".json", $CSVFileName); $JSONFileName = str_replace("csv/", "json/", $JSONFileName); $keys = array(); $newArray = array(); $data = csvToArray($CSVFileName, ','); $count = count($data) - 1; $labels = array_shift($data); foreach ($labels as $label) { $keys[] = $label; } $keys[] = 'id'; for ($i = 0; $i < $count; $i++) { $data[$i][] = $i; } for ($j = 0; $j < $count; $j++) { $d = array_combine($keys, $data[$j]); $newArray[$j] = $d; } $JSONVersion = json_encode($newArray); $fp = fopen($JSONFileName, "w+");
private function getTombstone($title) { if (!PreEighthRenderer::$titleToTombstone) { PreEighthRenderer::$titleToTombstone = csvToArray('data/preEighth/titleToTombstone.csv'); } return array_key_exists((string) strtolower($title), PreEighthRenderer::$titleToTombstone); }
private function getFrameDir($title, $set, $settings) { if (!EighthRenderer::$titleToFrameDir) { EighthRenderer::$titleToFrameDir = csvToArray('data/eighth/titleToAlternateFrame.csv'); } if (!EighthRenderer::$titleToTransform) { EighthRenderer::$titleToTransform = csvToArray('data/eighth/titleToTransform.csv'); } $frameDir = @EighthRenderer::$titleToFrameDir[(string) strtolower($title)]; if (!$frameDir) { $frameDir = 'transform-' . @EighthRenderer::$titleToTransform[(string) strtolower($title)]; } $timeshifted = explode(',', $settings['card.timeshifted.frames']); if (!$frameDir || $frameDir == 'transform-') { $frameDir = "regular"; } if ($frameDir == 'timeshifted' && in_array($set, $timeshifted) === FALSE) { $frameDir = "regular"; } return $frameDir; }
function csvToArray($file, $delimiter) { if (($handle = fopen($file, 'r')) !== FALSE) { $i = 0; while (($lineArray = fgetcsv($handle, 4000, $delimiter, '"')) !== FALSE) { for ($j = 0; $j < count($lineArray); $j++) { $arr[$i][$j] = $lineArray[$j]; } $i++; } fclose($handle); } return $arr; } // Do it $dataAlert = csvToArray($feed, ','); // Set number of elements (minus 1 because we shift off the first row) $count = count($dataAlert); //Use first row for names $labels = ["site", "node", "xalert", "yalert", "zalert"]; foreach ($labels as $label) { $keys[] = $label; } // Bring it all together for ($j = 0; $j < $count; $j++) { $dX = array_combine($keys, $dataAlert[$j]); $arrayAlert[$j] = $dX; } // Print as JSON data echo json_encode($arrayAlert); ?>
if ($confirm_name_response == 'no_possible_matches') { $no_matches = true; $rejected_all = true; } else { if (!$reset_match) { $confirmed_user_name = $confirm_name_response; } } } } $feed = 'https://docs.google.com/spreadsheets/d/1qYMG2XVmaK2GQMYATqCxa_kZu-ZptjUHF_o94_rKw2k/pub?gid=509740763&single=true&output=csv'; $keys = array(); //Array for Column Titles\ $myArr = array(); // Final Array $data = csvToArray($feed, ','); $count = count($data) - 1; //Store Column Titles $labels = array_shift($data); foreach ($labels as $label) { $keys[] = $label; } //Creat ID's $keys[] = 'id'; for ($i = 0; $i < $count; $i++) { $data[$i][] = $i; } //Combine Keys and Values for ($j = 0; $j < $count; $j++) { $d = array_combine($keys, $data[$j]); $myArr[$j] = $d;
define("TO_EMAIL", ""); // Email notification recipient define("SEND_TO_SLACK", true); // Enable/Disable instant slack notification define("SLACK_CHANNEL", "#general"); // Slack Channel define("SLACK_WEBHOOK_URL", ""); // Slack Webhook Url define("SEND_DAILY_EMAIL", true); // Send daily notification summary to Email define("SEND_DAILY_SLACK", true); // Send daily notification summary to Slack define("STATUS_SOURCE", "status.log"); // Status Log File /* End Config */ $data = csvToArray(); $result = prepareRunGoogle($data); if (SEND_TO_EMAIL) { resultsToEmail($result); } if (SEND_TO_SLACK) { resultsToSlack($result); } updateLog($data, $result); function csvToArray() { if (!file_exists(CSV_SOURCE) || !is_readable(CSV_SOURCE)) { // Check source and email error if issue occurs mail(TO_EMAIL, 'CSV Unreadable', 'Warning - URL Status Checker CSV "' . CSV_SOURCE . '" is unreadable/not found.'); } // Save data to array $data
function generate_json($doc, $bool) { $keys = array(); $array = array(); $csv = csvToArray($doc, ','); // Set number of elements (minus 1 because we shift off the first row) $count = count($csv) - 1; //Use first row for names $labels = array_shift($csv); foreach ($labels as $label) { $keys[] = $label; } // Bring it all together for ($j = 0; $j < $count; $j++) { $d = array_combine($keys, $csv[$j]); $nid = ''; if ($bool == true) { $id = $d['RIC.']; $pieces = explode(' ', $id); switch ($pieces[0]) { case 'C': $auth = 'crl'; break; case 'SA': $auth = 'sa'; break; case 'SS': $auth = 'ss'; break; case 'E': $auth = 'el'; break; case 'G': $auth = 'ge'; break; } $nid = 'ric.4.' . $auth . '.' . strtolower($pieces[2]); } if (strlen($nid) > 0) { $x = $nid; } else { $x = $j; } $array[$x] = $d; } return $array; }
/** * Api Call to Salesforce. * * @param $method * @param $url * @param array $options * @param array $debug_info * * @return array */ public function call_api($method, $url, $options = [], $debug_info = []) { try { if (is_null($options)) { $options = []; } $options['http_errors'] = false; $format = 'json'; if (isset($options['format'])) { $format = strtolower($options['format']); unset($options['format']); } //required so csv return matches json return when creating new records $lowerCaseHeaders = true; if (isset($options['lowerCaseHeaders'])) { $lowerCaseHeaders = $options['lowerCaseHeaders']; unset($options['lowerCaseHeaders']); } $response = $this->oauth2Client->{$method}($url, $options); /* @var $response \GuzzleHttp\Psr7\Response */ $headers = $response->getHeaders(); $response_code = $response->getStatusCode(); $data = ['operation' => '', 'success' => false, 'message_string' => '', 'http_status' => $response_code, 'raw_headers' => $headers, 'raw_body' => (string) $response->getBody()]; if ($format == 'xml') { $xml = simplexml_load_string((string) $response->getBody(), null, LIBXML_NOCDATA); $json = json_encode($xml); $response_array = json_decode($json, true); } elseif ($format == 'csv') { $response_array = csvToArray((string) $response->getBody(), $lowerCaseHeaders); } else { $response_array = json_decode((string) $response->getBody(), true); } if ($response_code == 200) { if (is_array($response_array)) { $data = array_replace($data, $response_array); } $data['success'] = true; $data['http_status'] = 200; } elseif ($response_code == 201) { if (is_array($response_array)) { $data = array_replace($data, $response_array); } $data['operation'] = 'create'; $data['success'] = true; $data['http_status'] = 201; if (isset($data['id'])) { //make responses more uniform by setting a newly created id as an Id field like you would see from a get $data['Id'] = $data['id']; } } elseif ($response_code == 204) { if (strtolower($method) == 'delete') { $data = array_merge($data, ['success' => true, 'operation' => 'delete', 'http_status' => 204]); } else { $data = array_merge($data, ['success' => true, 'operation' => 'update', 'http_status' => 204]); } } else { if (!is_array($response_array)) { $data = array_merge($data, ['message' => $response_array]); } elseif (count($response_array) > 1) { $data = array_merge($data, $response_array); } else { $data['raw_sfdc_error'] = (string) $response->getBody(); $data = array_merge($data, current($response_array)); } if ($data && isset($data['message'])) { $data['message_string'] = $data['message']; } elseif (!$data) { $data['message_string'] = (string) $response->getBody(); } $data['http_status'] = $response_code; $data['success'] = false; $data = array_merge($debug_info, $data); $this->log('error', 'Salesforce - ' . json_encode($data)); } if (isset($data) && $data) { $this->updateAccessToken($this->oauth2Client->getAccessToken()->getToken()); return $data; } } catch (Exception $e) { $data['message_string'] = $e->getMessage(); $data['file'] = $e->getFile() . ':' . $e->getLine(); $data['http_status'] = 500; $data['success'] = false; $data = array_merge($debug_info, $data); $this->log('error', 'Salesforce-Salesforce::call_api - ' . $e->getMessage() . ' - ' . $e->getFile() . ':' . $e->getLine()); return $data; } return []; }
function insertarCsv($url, $nombre, $delimiter) { // Set your CSV feed $feed = $url; // Arrays we'll use later $keys = array(); $newArray = array(); // Function to convert CSV into associative array function csvToArray($file, $delimiter) { if (($handle = fopen($file, 'r')) !== FALSE) { $i = 0; while (($lineArray = fgetcsv($handle, 4000, $delimiter, '"')) !== FALSE) { for ($j = 0; $j < count($lineArray); $j++) { $arr[$i][$j] = $lineArray[$j]; } $i++; } fclose($handle); } return $arr; } // Do it $data = csvToArray($feed, $delimiter); //$delimiter indica el simbolo de separacion de datos (, o ;) // Set number of elements (minus 1 because we shift off the first row) $count = count($data) - 1; //Use first row for names $labels = array_shift($data); foreach ($labels as $label) { $keys[] = $label; } // Add Ids, just in case we want them later $keys[] = 'id'; for ($i = 0; $i < $count; $i++) { $data[$i][] = $i; } // Bring it all together for ($j = 0; $j < $count; $j++) { $d = array_combine($keys, $data[$j]); $newArray[$j] = $d; } //print_r($newArray); $csv = $newArray; $procesar = print_r($csv[0], true); //convertir a string (primer trozo) para sacar los nombres de las cabeceras $find1 = '['; $find2 = ']'; $pos1 = 0; $pos2 = 0; $contar = 0; $i = 0; $lon = 0; $lat = 0; $dir = ''; while (true) { $pos1 = strpos($procesar, $find1, $contar); $pos2 = strpos($procesar, $find2, $contar); if ($pos2 === false) { break; } $contar = $pos2 + 1; $array[$i] = substr($procesar, $pos1 + 1, $pos2 - $pos1 - 1); //obtener nombre cabecera $i++; } //asignar 'titulo' $datos = $array[0]; /// for ($j = 0; $j < count($array); $j++) { //buscar latitud y longitud por nombre if ($array[$j] == "Longitud") { $lon = $array[$j]; } if ($array[$j] == "Latitud") { $lat = $array[$j]; } } //buscar latitud y longitud por numeros for ($j = 0; $j < count($array); $j++) { if ($lon === 0 || $lat === 0) { if (is_numeric($csv[0][$array[$j]])) { $check = floatval($csv[0][$array[$j]]); if ($check < -16 && $check > -17) { $lon = $array[$j]; } if ($check > 28 && $check < 29) { $lat = $array[$j]; } } } //buscar direccion if ($array[$j] == "Dirección" || $array[$j] == "Direccion") { $dir = $array[$j]; } /// } include '../conexion/conexion.php'; //crear tabla si no existe $query = @("CREATE TABLE IF NOT EXISTS " . $nombre . "\n\t\t\t(id int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n\t\t\tlon float not null,\n\t\t\tlat float not null,\n\t\t\tdir varchar(200) CHARACTER SET utf8 COLLATE utf8_unicode_ci not null,\n\t\t\tdatos varchar(50) CHARACTER SET utf8 COLLATE utf8_unicode_ci not null\n\t\t\t)\n\t\t\tDEFAULT CHARSET=utf8;"); $conexion->query($query) or die('Fallo al crear la tabla' . $conexion->error . '<br/>'); /// //insertar datos en la tabla for ($i = 0; $i < count($csv); $i++) { $direccion = $csv[$i][$dir]; $informacion = $csv[$i][$datos]; $direccion = str_replace("'", '"', $direccion); //intercambia comillas simples por dobles para evitar problemas en las inserciones $informacion = str_replace("'", '"', $informacion); if ($lon === 0 && $lat === 0) { $longitud = 0; $latitud = 0; } else { $longitud = $csv[$i][$lon]; $latitud = $csv[$i][$lat]; } $query = @("INSERT INTO " . $nombre . " values ('NULL',{$longitud},{$latitud},'{$direccion}','{$informacion}')"); $conexion->query($query) or die('Fallo al insertar registros en la tabla. ' . $conexion->error . '<br/>'); } //guardar el nombre de la tabla $query = @"CREATE TABLE IF NOT EXISTS nombretablas\n\t\t\t(id int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n\t\t\tnombre varchar(20) CHARACTER SET utf8 COLLATE utf8_unicode_ci not null UNIQUE\n\t\t\t)\n\t\t\tDEFAULT CHARSET=utf8;"; $conexion->query($query) or die('Fallo al crear la tabla: nombretablas' . $conexion->error . '<br/>'); //insertar nombre de la tabla $query = @"INSERT INTO nombretablas values ('NULL','{$nombre}')"; $conexion->query($query) or die('Fallo al insertar el registro en nombretablas' . $conexion->error . '<br/>'); /// $conexion->close(); //cerrar la conexion con la db$conexion echo "Fin del proceso. <br />"; }
private function getFrameDir($title, $set, $settings) { if (!PlanesWalkerRenderer::$titleToTransform) { PlanesWalkerRenderer::$titleToTransform = csvToArray('data/eighth/titleToTransform.csv'); } $frameDir = 'transform-' . @PlanesWalkerRenderer::$titleToTransform[(string) strtolower($title)]; if (!$frameDir || $frameDir == 'transform-') { $frameDir = "regular"; } return $frameDir; }
function getPenaltyLUT() { if (!is_array($this->penaltyLUT)) { $this->penaltyLUT = csvToArray($this->penaltyLUT); } return $this->penaltyLUT; }
function isCompatible($fileContents, $dataArray) { if (numRows($dataArray) == 0) { return true; } if (numRowsCSV($fileContents) == numRows($dataArray)) { $csvArray = csvToArray($fileContents); return compatibleDateTimes($dataArray, $csvArray); } else { return false; } }