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. ;)
Related
This is the data in the text file contain the data
I have already store the data in the array
enter image description here
<?php
if (!(isset($_GET['job_title']) && empty($_GET['job_title']))) {
$job_title = $_GET['job_title'];
echo $job_title;
$filename = __DIR__ . '/jobpost.txt';
if (file_exists($filename)) {
$data= null;
$allData = array();
$handle = fopen($filename, "r");
while (!feof($handle)) {
$onedata = fgets($handle);
if ($onedata != "") {
$data = explode("\t", $onedata);
$allData[] = $data;
}
}
echo "<pre>";
print_r($allData);
echo "</pre>";
} else {
echo "file does not exist";
}
} else {
echo "<p class=\"bg_danger\"> must enter the job title </p>";
}
?>
My question is when user enter an input "software engineering" and based on the input value, must retrieve the related the array.
First don't forget to filter/sanitize your user inputs.
Now Check while storing data into the array if you can create a array with keys as "software engineering"
if that's not possible you can loop through array once & create array you need
$arrNewDataArray = [];
foreach( $dataArray as $arr ){
$arrNewDataArray[$arr[1]] = $arr;
}
Then you will be able to check if user input value is present in the array & retrieve it like below.
$userinput = 'software engineering';
$arrayYouNeed = [];
if( isset( $arrNewDataArray[$userinput] ) ) {
$arrayYouNeed = $arrNewDataArray[$userinput];
}
I am storing some data in an array and I want to add the key to it if the title already exists in the array. But for some reason it's not adding the key to the title.
Here's my loop:
$data = [];
foreach ($urls as $key => $url) {
$local = [];
$html = file_get_contents($url);
$crawler = new Crawler($html);
$headers = $crawler->filter('h1.title');
$title = $headers->text();
$lowertitle = strtolower($title);
if (in_array($lowertitle, $local)) {
$lowertitle = $lowertitle.$key;
}
$local = [
'title' => $lowertitle,
];
$data[] = $local;
}
echo "<pre>";
var_dump($data);
echo "</pre>";
You will not find anything here:
foreach ($urls as $key => $url) {
$local = [];
// $local does not change here...
// So here $local is an empty array
if (in_array($lowertitle, $local)) {
$lowertitle = $lowertitle.$key;
}
...
If you want to check if the title already exists in the $data array, you have a few options:
You loop over the whole array or use an array filter function to see if the title exists in $data;
You use the lowercase title as the key for your $data array. That way you can easily check for duplicate values.
I would use the second option or something similar to it.
A simple example:
if (array_key_exists($lowertitle, $data)) {
$lowertitle = $lowertitle.$key;
}
...
$data[$lowertitle] = $local;
I am using parse_ini_file to parse an ini file using PHP.
Now I first upload an INI file to my server then open it and allow user to mak custom changes to the file.
Now once users has edited the file i get the data from post and save the file back to server. But Now i dont get my sections. INIdetails,Dialplan in the updated file so when i also want to write that to file how to do that?
This is the code :
$this->data['parameters'] = parse_ini_file($path.$filename,true);
/*Getting Our POST DATA from View*/
$data = array(
'SipUserName' => $this->input->post('SipUserName') ,
'SipAuthName' => $this->input->post('SipAuthName'),
'DisplayName' => $this->input->post('DisplayName'),
'Password' => $this->input->post('Password'),
'Domain' => $this->input->post('Domain'),
'Proxy' => $this->input->post('Proxy'),
'Port' => $this->input->post('Port'),
'ServerMode' => $this->input->post('ServerMode'),
'Param_1' => $this->input->post('Param_1'),
'Param_2' => $this->input->post('Param_2')
);
/*Creating New file with the name of customer loggedin*/
$name = $this->session->userdata('username');
$ext = $this->session->userdata('extension');
$custom_file = fopen('uploads/'.$name.'_'.$ext.'.ini', 'w');
fwrite($custom_file, "[INIDetails]\n");
foreach ($data as $key => $value)
{
fwrite($custom_file, " $key = $value\n");
}
fclose($custom_file);
/*Setting path to New CUSTOM file with customer name as prefix*/
$file = $path.$custom_file;
function write_php_ini($array, $file)
{
$res = array();
foreach($array as $key => $val)
{
if(is_array($val))
{
$res[] = "[$key]";
foreach($val as $skey => $sval) $res[] = "$skey = ".(is_numeric($sval) ? $sval : '"'.$sval.'"');
}
else $res[] = "$key = ".(is_numeric($val) ? $val : '"'.$val.'"');
}
safefilerewrite($file, implode("\r\n", $res));
}
function safefilerewrite($fileName, $dataToSave)
{ if ($fp = fopen($fileName, 'w'))
{
$startTime = microtime(TRUE);
do
{ $canWrite = flock($fp, LOCK_EX);
// If lock not obtained sleep for 0 - 100 milliseconds, to avoid collision and CPU load
if(!$canWrite) usleep(round(rand(0, 100)*1000));
} while ((!$canWrite)and((microtime(TRUE)-$startTime) < 5));
//file was locked so now we can store information
if ($canWrite)
{ fwrite($fp, $dataToSave);
flock($fp, LOCK_UN);
}
fclose($fp);
}
}
/*Creates ini file, dumps array to string and creates .INI file*/
write_php_ini($data,$file);
The culprit from your previous code is that your array is not formatted correctly, it should be array of arrays to achieve what you want.
Try below code:
// First read the ini file that the user was editing
// Your idea to read the existing ini file is good, since it will generate you the structured array
$previous_data = parse_ini_file($path . $filename, true);
// Overwrite/edit the previous_data using user's post data
$previous_data['INIDetails']['SipUserName'] = $this->input->post('SipUserName');
$previous_data['INIDetails']['Password'] = $this->input->post('Password');
$previous_data['INIDetails']['Domain'] = $this->input->post('Domain');
$previous_data['INIDetails']['Proxy'] = $this->input->post('Proxy');
$previous_data['INIDetails']['Port'] = $this->input->post('Port');
$previous_data['INIDetails']['SipAuthName'] = $this->input->post('SipAuthName');
$previous_data['INIDetails']['DisplayName'] = $this->input->post('DisplayName');
$previous_data['INIDetails']['ServerMode'] = $this->input->post('ServerMode');
$previous_data['INIDetails']['UCServer'] = $this->input->post('UCServer');
$previous_data['INIDetails']['UCUserName'] = $this->input->post('UCUserName');
$previous_data['INIDetails']['UCPassword'] = $this->input->post('UCPassword');
$previous_data['DialPlan']['DP_Exception'] = $this->input->post('DP_Exception');
$previous_data['DialPlan']['DP_Rule1'] = $this->input->post('DP_Rule1');
$previous_data['DialPlan']['DP_Rule2'] = $this->input->post('DP_Rule2');
$previous_data['DialPlan']['OperationMode'] = $this->input->post('OperationMode');
$previous_data['DialPlan']['MutePkey'] = $this->input->post('MutePkey');
$previous_data['DialPlan']['Codec'] = $this->input->post('Codec');
$previous_data['DialPlan']['PTime'] = $this->input->post('PTime');
$previous_data['DialPlan']['AudioMode'] = $this->input->post('AudioMode');
$previous_data['DialPlan']['SoftwareAEC'] = $this->input->post('SoftwareAEC');
$previous_data['DialPlan']['EchoTailLength'] = $this->input->post('EchoTailLength');
$previous_data['DialPlan']['PlaybackBuffer'] = $this->input->post('PlaybackBuffer');
$previous_data['DialPlan']['CaptureBuffer'] = $this->input->post('CaptureBuffer');
$previous_data['DialPlan']['JBPrefetchDelay'] = $this->input->post('JBPrefetchDelay');
$previous_data['DialPlan']['JBMaxDelay'] = $this->input->post('JBMaxDelay');
$previous_data['DialPlan']['SipToS'] = $this->input->post('SipToS');
$previous_data['DialPlan']['RTPToS'] = $this->input->post('RTPToS');
$previous_data['DialPlan']['LogLevel'] = $this->input->post('LogLevel');
// Set Name of New file with the name of customer logged in
$name = $this->session->userdata('username');
$ext = $this->session->userdata('extension');
$custom_file = "$name_$ext.ini";
$new_filename = $path . $custom_file;
// Write the INI file
write_php_ini($data, $new_filename);
function write_php_ini($array, $new_filename)
{
$res = array();
foreach ($array as $key => $val) {
if (is_array($val)) {
$res[] = "[$key]";
foreach ($val as $skey => $sval) {
$res[] = "$skey = " . (is_numeric($sval) ? $sval : '"' . $sval . '"');
}
} else {
$res[] = "$key = " . (is_numeric($val) ? $val : '"' . $val . '"');
}
}
safefilerewrite($new_filename, implode("\r\n", $res));
}
function safefilerewrite($new_filename, $dataToSave)
{
if ($fp = fopen($new_filename, 'w')) {
$startTime = microtime(true);
do {
$canWrite = flock($fp, LOCK_EX);
// If lock not obtained sleep for 0 - 100 milliseconds, to avoid collision and CPU load
if (!$canWrite) {
usleep(round(rand(0, 100) * 1000));
}
} while ((!$canWrite) and ((microtime(true) - $startTime) < 5));
//file was locked so now we can store information
if ($canWrite) {
fwrite($fp, $dataToSave);
flock($fp, LOCK_UN);
}
fclose($fp);
}
}
From your previous code, there are bunch of inappropriate codes which I remove. Also, too many inconsistencies like Method naming, variable naming etc.
If your function was named Camel cased then through out your code it must be named as camel-cased. If your variables are with underscore, then through out your code, they must have underscore for two or more worded variable.
I didn't edit the naming convention of your code so you won't be confused but i suggest to have a consistent naming convention through out your project.
UPDATED:
based on your answer, it seems like you changed your whole code. I would like to provide another way using nested foreach and passing by reference that save couple of lines:
$this->data['params'] = $this->parameter_m->get();
$this->data['parameters'] = parse_ini_file($path . $filename, true);
foreach ($this->data['parameters'] as $key_header => &$value_header) {
foreach ($value_header as $key_item => &$value_item) {
$value_item = $this->input->post($key_item);
}
}
$this->load->helper('file');
$this->load->library('ini');
$file = $path . $filename;
$ini = new INI($file);
$ini->read($file);
$ini->write($file, $this->data['parameters']);
Finally i got an answer:
I will loop through what i get from POST and will get each array's key. And then i will give the resultant to my Write Method
$this->data['params'] = $this->parameter_m->get();
/*Getting the parameters to display on view*/
$this->data['parameters'] = parse_ini_file($path.$filename,true);
while (current($this->data['parameters']) )
{
$param_set = current($this->data['parameters']);
$param_type = key($this->data['parameters']);
foreach ($param_set as $key =>$value)
{
$this->data['parameters'][$param_type][$key] = $this->input->post($key);
}
next($this->data['parameters']);
}
$this->load->helper('file');
$this->load->library('ini');
$file = $path.$filename;
$ini = new INI($file);
$ini->read($file);
$ini->write($file, $this->data['parameters']);
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);
}
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;
}