I am trying to read a csv file line by line and save its content in an array. I then parse the array using foreach to print each line.
However, when i try to send the variable(which according to me should be a string) to the deleteInstance method it prints as an array and not plain string.
I have issue sending this to Softlayer API since it throw me an error saying string expected but array given ? I am not sure what is wrong
a.csv
7381838
7381840
7381842
php
<?PHP
require_once dirname(__FILE__) . '/SoftLayer/SoapClient.class.php';
function readCSV($csvFile){
$file_handle = fopen($csvFile, 'r');
while (!feof($file_handle) ) {
$line_of_text[] = fgetcsv($file_handle, 1024);
}
fclose($file_handle);
return $line_of_text;
}
// Set path to CSV file
$csvFile = 'a.csv';
$csv = readCSV($csvFile);
foreach ($csv as $value) {
var_dump($value);
print_r($value);
deleteInstance($value);
}
function deleteInstance($ccid){
$apiUsername = 'xxxxx';
$apiKey = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$cancelRightNow = true; //or false if you want to wait till the billing cycle ends
$cloudComputingInstanceId = $ccid;
print_r($cloudComputingInstanceId);
var_dump($cloudComputingInstanceId);
$client = SoftLayer_SoapClient::getClient('SoftLayer_Virtual_Guest', $cloudComputingInstanceId, $apiUsername, $apiKey);
$objectMask = new SoftLayer_ObjectMask();
$objectMask->billingItem;
$client->setObjectMask($objectMask);
$cci = $client->getObject();
$client = SoftLayer_SoapClient::getClient('SoftLayer_Billing_Item', $cci->billingItem->id, $apiUsername, $apiKey);
$billingItem = $client->getObject();
if ($billingItem != null) {
if ($cancelRightNow) {
$client->cancelService();
} else {
$client->cancelServiceOnAnniversaryDate();
}
}
}
?>
The problem is your argument to deleteInstance is an array... It looks like this:
$csv = Array(
0 => Array(0 => '7381838'),
1 => Array (0 => '7381840'),
2 => Array(0 => '7381842')
)
This is because you are parsing it as CSV which splits each line into an array based on a delimiter. This is not what you want. Instead use file to read each line into an array:
function readCSV($csvFile){
return file($csvFile);
}
$csv = readCSV('a.csv');
foreach ($csv as $value) {
// your value is now the line of the file like '7381838'
deleteInstance($value);
}
Try this and see what happens
foreach ($csv as $value) {
$svalue = $value[0];
var_dump($svalue);
print_r($svalue);
deleteInstance($svalue);
}
Related
I want to write $totalToday data from API to csv file. If current date not existed, append new record for current date. I've came with following solution.
$search = date("d/m/Y");
$lines = file('data.csv');
$line_number = false;
foreach($lines as $key => $line) {
$line_number = (strpos($line, $search) !== FALSE);
}
if(!$line_number){
$entry = array(date("d/m/Y"), $totalToday);
$fp = fopen('data.csv', 'a');
fputcsv($fp, $entry);
fclose($fp);
}
My problem is $totalToday from API get updated time to time. I want to record the latest update. so I replaced $search = date("d/m/Y"); with $search = date("d/m/Y"), $totalToday now I have multiple record for same date in my data.csv. I want to overwrite the current date record with very latest data without append to new line. How to accomplish my requirement
Example data: (first rows)
date,newCases,totalToday
13/04/2020,21,110
14/04/2020,26,125
14/04/2020,30,130
I want to replace 14/04/2020,26,125 with 14/04/2020,30,130
One approach could be this:
<?php
$search = '14/04/2020';
$other_data_from_api = array(188,102);
$lines = file('data.csv');
//Create a new array and set all dates as keys
//The latest set key would be the current
$new_arr = array();
foreach($lines as $line) {
$exp = explode(',', $line);
$new_arr[$exp[0]] = array($exp[1], $exp[2]);
}
/*
So in your example:
13/04/2020,21,110
14/04/2020,26,125
14/04/2020,30,130
the array $new_arr would contain:
[13/04/2020] => Array
(
[0] => 21
[1] => 110
)
[14/04/2020] => Array
(
[0] => 30
[1] => 130
)
*/
//Rewrite the whole file with values from this new array
$fp = fopen('data.csv', 'w');
foreach($new_arr as $key=>$line) {
$entry = $key . ',' . implode(',', $line);
fputs($fp, $entry);
}
fclose($fp);
You could also:
//Rewrite the whole file with values from this new array
//And include the actual data from the API
//(Then 188,102 would be included with the data of the $search variable)
$fp = fopen('data.csv', 'w');
foreach($new_arr as $key=>$line) {
if ($search == $key) {
$entry = $search . ',' . implode(',', $other_data_from_api);
}
else {
$entry = $key . ',' . implode(',', $line);
}
fputs($fp, $entry);
}
fclose($fp);
I tried the code in this way. Now it writes a part of the first csv in the second but i don't understand because it doesn't not copy all.
Why?
// Sopprimo gli errori del php
//error_reporting(0);
// Includo la libreria
require_once 'excel_reader2.php';
$file_handle = fopen("SATconcluse.csv", "r");
while (!feof($file_handle) ) {
$line_of_text = fgetcsv($file_handle, 0);
$arr = array('Nr SAT' => $line_of_text[0],'Data Apertura' => $line_of_text[13], 'Tipo Servizio' => $line_of_text[1], 'Stato SAT' => $line_of_text[2],'Marca Terminale' => $line_of_text[4], 'Modello Terminale' => $line_of_text[5], 'IMEI guasto' => $line_of_text[6],'IMEI consegnato' => $line_of_text[7],'Famiglia guasto' => $line_of_text[8],'Descrizione guasto' => $line_of_text[9] );
$data[] = $arr;
}
fclose($file_handle);
$file = fopen("eccomiquacisono.csv","w");
foreach ($data as $arr){
fputcsv($file,$arr);
}
fclose($file);
Use fgetcsv to load your file in an array, and then carry on with your processing. If you areusing PHP5, you can simply set the second parameter to 0 to get the whole line:
$line_of_text = fgetcsv($file_handle, 0);
Likewise, use fputcsv to save individual records in a CSV file.
In your code, you are trying to fill in a file with an empty array. You probably meant to add each $arr in $data sequentially:
$data[] = $arr;
And then loop on each entry and put it in the other file:
foreach ($data as $arr)
fputcsv($file,$arr);
The whole code thus would be:
$data = array();
while (!feof($file_handle) ) {
$line_of_text = fgetcsv($file_handle, 0);
$arr = array(...);
$data[] = $arr;
}
fclose($file_handle);
$file = fopen("eccomiquacisono.csv","w");
foreach ($data as $arr)
fputcsv($file,$arr);
fclose($file);
I have this big file containing SWIFT numbers and bank names. I'm using the following php function for reading and comparing data:
function csv_query($blz) {
$cdata = -1;
$fp = fopen(DIR_WS_INCLUDES . 'data/swift.csv', 'r');
while ($data = fgetcsv($fp, 1024, ",")) {
if ($data[0] == $blz){
$cdata = array ('blz' => $data[0],
'bankname' => $data[7]);
// 'prz' => $data[2]
}
}
return $cdata;
}
The csv files looks like that:
"20730054",1,"UniCredit Bank - HypoVereinsbank (ex VereinWest)","21423","Winsen (Luhe)","UniCredit Bk ex VereinWest",,"HYVEDEMM324","68","013765","M",1,"20030000"
"20750000",1,"Sparkasse Harburg-Buxtehude","21045","Hamburg","Spk Harburg-Buxtehude","52002","NOLADE21HAM","00","011993","U",0,"00000000"
"20750000",2,"Sparkasse Harburg-Buxtehude","21605","Buxtehude","Spk Harburg-Buxtehude","52002",,"00","011242","U",0,"00000000"
As you can see from the code, I need the first and the eight string. If the first string has no duplicates everything is ok, but if it has, most likely the eighth field of the duplicate will be empty and I get no result back. So I want to ask how to display that eighth field of the first result if the line has a duplicate.
I guess this will solve your problem :
function csv_query($blz) {
$cdata = -1;
$fp = fopen(DIR_WS_INCLUDES . 'data/swift.csv', 'r');
$counter = 0; // add this line
while ($data = fgetcsv($fp, 1024, ",")) {
if ($data[0] == $blz && !$counter) { //change this line
$cdata = array(
'blz' => $data[0],
'bankname' => $data[7]
);
$counter++; //add this line
}
}
return $cdata;
}
I know there are a lot of resources out there for putting a CSV into an associative array, but I can't find anything that helps a noob like me do exactly what I want to do.
I currently have an associative array defined inside my PHP file:
$users = array(
'v4f25' => 'Stan Parker',
'ntl35' => 'John Smith',
);
I would like to move that array into a CSV file (users.txt) so:
v4f25, Stan Parker
ntl35, John Smith
The next step is to import users.txt so I can use it precisely like I was using the array $users.
Any help here? The last code I tried returned this: (which is not what I want)
array(2) {
["v4f25"]=>
string(5) "ntl35"
["Stan Parker"]=>
string(10) "John Smith"
}
What about the following?
$data = array();
if ($fp = fopen('csvfile.csv', 'r')) {
while (!feof($fp)) {
$row = fgetcsv($fp);
$data[$row[0]] = $row[1];
}
fclose($fp);
}
$users = array(
'v4f25' => 'Stan Parker',
'ntl35' => 'John Smith',
);
$fp = fopen('users.txt', 'w');
if ($fp) {
foreach ($users as $key => $value) {
fputcsv($fp, array($key, $value));
}
fclose($fp);
} else {
exit('Could not open CSV file')
}
See: fputcsv()
UPDATE - in the comments you're interested in how to read the file and get your users back out. Here's the return trip:
$users = array();
if (($handle = fopen("my-csv-file.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$users[$data[0]] = $data[1];
}
fclose($handle);
} else {
exit('Could not open CSV file');
}
if (count($users) == 0) {
exit('CSV file empty: no users found');
}
Here's a solution using fputcsv() which flattens the key/value pairs to an array before writing to disk.
$filehandle = fopen("csvfile.csv", "w");
if ($filehandle) {
foreach ($users as $key => $value) {
fputcsv($filehandle, array($key, $value);
}
fclose($filehandle);
}
else // couldn't open file
Try this (assuming your strings contain no commas):
$users = array(
'v4f25' => 'Stan Parker',
'ntl35' => 'John Smith',
);
foreach ($users as $k => $v) {
print "$k, $v\n";
}
Obviously you could then create the CSV file like so:
php above_script.php > outfile.csv
Now, to get from CSV back into an array you could use something like:
$file = 'outfile.csv';
$arr = array();
if (file_exists($file)) {
foreach (explode("\n", file_get_contents($file)) as $l) {
list($k, $v) = explode(',', $l);
$arr[trim($k)] = trim($l);
}
}
print_r($arr, true);
NOTES:
If your strings do (or might) contain commas, then you'll probably want to use a PHP builtin function to decode them - in which case the answers by harald and artlung are useful.
RFC 4180 describes how commas (and other values) are encoded in CSV, in case you want to roll your own CSV encoding/decoding functions for whatever reason.
I have a configuration file like the following,
NameA=3
NameB=2
NameC=1
The following code tries to find NameC, and replace its value. Suppose here I pass in the value 0.
public function writeScreenSwitch($isTick)
{
$filename = 'my/file/path';
$data = parse_ini_file($filename);
$replace_with = array(
'NameC' => $isTick
);
// After print out $replace_with value, I'm sure the value is,
// [NameC] => 0
$fh = fopen($filename, 'w');
foreach ( $data as $key => $value )
{
if ( !empty($replace_with[$key]) ) {
$value = $replace_with[$key];
} else {
echo "array empty";
// the problem is here.
// $replace_with[$key] is always empty.
// but before the loop, the value $replace_with['NameC']=0
// why.
}
fwrite($fh, "{$key}={$value}" . PHP_EOL);
}
fclose($fh);
}
I have described the problem on the code.
Because 0 is counted as EMPTY. That's why you are getting this.
Check here
The problem is with the empty() function, have a look at the remarks in the Return Values section.
What you're needing to check for is if it is set, using the isset() function:
public function writeScreenSwitch($isTick)
{
$filename = 'my/file/path';
$data = parse_ini_file($filename);
$replace_with = array(
'NameC' => $isTick
);
// After print out $replace_with value, I'm sure the value is,
// [NameC] => 0
$fh = fopen($filename, 'w');
foreach ( $data as $key => $value )
{
if ( isset($replace_with[$key]) ) {
$value = $replace_with[$key];
} else {
echo "array not set";
// the problem is here.
// $replace_with[$key] is always empty.
// but before the loop, the value $replace_with['NameC']=0
// why.
}
fwrite($fh, "{$key}={$value}" . PHP_EOL);
}
fclose($fh);
}
That should do the trick. ;)