This is the contents of my file spectrum_info.txt:
raid,spectrum/raid_info.txt
rbid,spectrum/rbid_info.txt
rcid,spectrum/rcid_info.txt
rdid,spectrum/rdid_info.txt
reid,spectrum/reid_info.txt
When I load this file data using below code
$s_types=file('spectrum/spectrum_info.txt');
$i=0;
foreach($s_types as $s_type)
{
$s_arrfields = explode(',', $s_type);
$s_names[] = $s_arrfields[0];
$sf_names[] = $s_arrfields[1];
}
I put file_names information from the above file into $sf_names array.
Manually I created one other array having same data:
$f_temp=array("spectrum/raid_info.txt",
"spectrum/rbid_info.txt",
"spectrum/rcid_info.txt",
"spectrum/rdid_info.txt",
"spectrum/reid_info.txt",
"spectrum/rfid_info.txt",
"spectrum/rgid_info.txt",
"spectrum/rhid_info.txt");
print_r($f_temp);
echo"<br/>";
print_r($sf_names);
echo"<br/>";
$result=array_diff($f_temp,$sf_names);
print_r($result);
Both arrays are having same data. Still array_diff() shows all array elements as being different.
I'm trying this because, when i used $sf_names file information to read data from that particular file I get the below error.
Warning: file(spectrum/raid_info.txt ): failed to open stream: Invalid argument
Please help me regarding array_diff() as how to change data loaded from a file equal to manually created array. It can be useful in solving the above error. Thanks.
The values returned by file(), by default, contain the newline character at the end of each line. The FILE_IGNORE_NEW_LINES flag can be used to drop the newline from each value.
$s_types = file('spectrum/spectrum_info.txt', FILE_IGNORE_NEW_LINES);
For full details, see http://php.net/manual/en/function.file.php
Related
I need to do a report sing php & pdf based on another coder's(asp) data in mysql.
$Mysqldata_Field1:[{"name":"alex","age":"30","pic":"filename.ext"}, {"name":"alice","age":"29","pic":"filename.ext"}]
I need to extract all the "pic" value from the array above which is stored in mysql.
What is the best approach?
I have tried this
$img=json_decode($Mysqldata_Field1,true);
foreach($img as $item=>$pic)
{
$images .= $pic["pic"].",";
}
But I'm getting error:
Invalid argument supplied for foreach()
Thanks to both the suggestion.
var_dump showed that the $mysqldata_Field1 contains both array for some records and some strings (incomplete array).
managed to correct those data entry to make a complete array, then the script worked.
this time its not the code issue, its the data entry.
This is a tricky one...I am trying to replace some strings in a file that i hold in array.
Because there are a lot of files...i've been trying to find the fastest way possible.
I tried this (which worked) but it was slow.
First parsed all the files and got an array of the values i want to
change (lets say 500).
Then I wrote a foreach loop to parse through the files one by one.
Then inside that, another foreach loop to go through the values one by one
preg_replacing the file for any occurrences of the array value.
This takes forever though cause not all files need to be parsed with 500 array elements.
So i am changing the code now like this:
Parse every file and make an array of the values i want to replace.
Search the file again for all the occurrences for each array value and replace it.
Save the file
I think this will be much faster that the old way...The problem i am having though now is with the read/write loop, and the array loop...
I want to do this as fast as possible...cause there will be a lot of files to parse and some have 100+ values.
So far i got this in a function.
function openFileSearchAndReplace($file)
{
$holdcontents = file_get_contents($file);
$newarray = makeArrayOfValuesToReplace($holdcontents);
foreach ($newarray as $key => $value) {
$replaceWith = getNewValueFor($value);
$holdcontent = preg_replace('/\\b'.$value.'\\b/', $replaceWith, $holdcontents);
}
file_put_contents($file, $holdcontent, LOCK_EX); //Save and close
}
Now, this doesnt work...it just changes 1 value only because i have file_put_contents and file_get_contents outside of the foreach. (Not to mention that it replaces values that it shouldnt replace. Probably cause the read/write are outside of the loop.) I have to put them inside to work..but thats gonna be slow..cause it take 3-4seconds per file to do the change since there are a lot of elements in the array.
How can i "Open the file", "Read it", "Change ALL values first", "Then save close the file", so i can move to the next.
EDIT:
Maybe i am not explaining it well i dont know...or is this too complicated....I have to parse the array of values...there is no way i can avoid that...but instead of (In every loop), i open the file search and replace 1 value, close the file.....I want to do this:
Open the file, get the content in an array or string or whatever. For all the values i have keep replacing the text with the equivalent value, and when all the values are done...that array or string write to the file. So i am only opening/closing the file once. Instead of waiting for php to read/write/close all the time.
-Thanks
How about just using str_replace(mixed $search , mixed $replace , mixed $subject)?
You can have an array of search strings which will be replaced by their corresponding item in the replace array and as the PHP manual says:
If you don't need fancy replacing rules (like regular expressions), you should always use this function instead of preg_replace().
Also just close the file and reopen it with mode 'w'. File will be truncated to 0 length
Added Edit
$fileContents = file_get_contents("theFile");
$search = array('apples', 'oranges');
$replace = array('pears', 'lemons');
$newContents = str_replace($search, $replace, $fileContents);
$handle = fopen("theFile","w");
fwrite($handle, $newContents);
fclose($handle);
That's it your file has all the old strings replaced with new ones.
There is no solution to the problem. file_get_contents and file_put_contents simply doesnt work like that.
I appreciate everyone's attention to the problem.
I have a php file that has an array in it. I'd like to be able to add an item to that array using a simple form.
Here is an example similar to my array:
$list = array("BA0UKSF","BA9IHHE","BAC8GMB","BAC8HMC","BAC8HMC","BAC8HMC","BACI60T","BAEIDFD","BAEIEFE","BAEIEFE","BAMB0","BAOUKSE","BAOUKSF","BAPQADL","BAPQADM","BUNDLE","CN3ICDC","CN3ICDCA","CN7IZDPA","CN8ID42","CN8ID72","CNECBCBA");
I'd like to add the new item to the array someplace either at the beginning or end of the array list.
I know how to pass the forms data to php but what I dont know is how to get php to open this file, locate the array and add something to it.
I'd just store your array data in JSON format what makes it very easy to operate on the array.
Reading array:
$list = json_decode(file_get_contents($file));
Saving array:
file_put_contents($file, json_encode($list));
Reasons:
It is very bad practice to patch PHP code. (difficult to maintain; will possibly stop to work as you change the code in the file etc.)
If your input you add to $list is user-input and not 100% validated, it may be malicious code in it...
You can parse the text file line by line and locate the array first. And then, you can simply use:
array_push() -- if you want to add elements to the end of the array
array_unshift() - if you want to add elements to the beginning of the array
Examples:
array_push($list, "CN7IZDPA"); //adding to the end
array_unshift($list, "CN7IZDPA"); //adding to the beginning
But reading your array definition from a text file seems like a bad idea. You really should use a database as it makes managing the stuff easier.
Hope this helps!
I have the following CSV file:
08-0018421032;00-0018151831;G-20009429-0;G-20009429-0;0374048-0
27-001842101232;10-0018151831;G-30009429-0;G-50009429-0;7374048-0
36-0018421033232;20-0018151831;G-40009429-0;G-60009429-0;8374048-0
As you can see the separator is the ; symbol.
I then send this info to php via a jquery plugin which works perfect since I can read the file in PHP. The following code grabs the CSV file (Which is the $csvfile variable) and I can see the lines in it:
$file = fopen("upload/$csvfile", "r");
while (!feof($file) ) {
$line = fgetcsv($file, 1024,';');
print $line[0].'<br/>';
}
fclose($file);
What I need is to be able to select not only the line but on the value in it. To go to a specific value, for example in the first line the 3rd value would be G-20009429-0 and I would assign this to a php variable to be used later on.
Right now I have no idea how to grab a specific value in a line and also when I print the $line[0] it shows the values in a vertical order instead of a horizontal order. What I mean with this is that it shows the following output:
00-0018151831
10-0018151831
20-0018151831
Instead of showing me like this:
08-0018421032;00-0018151831;G-20009429-0;G-20009429-0;0374048-0
Maybe is the sleep but am stuck here. Just to repeat, the csv file is read by Php correctly since I can do a print_r on it and it shows all the lines in it. The thing is how to manipulate the information after I have the csv and how to grab a specific value in a specific line. Thank you.
$line is an array containing every element from that row. $line[0] is the first element of the row, $line[1] the second element and so on. Try var_dump($line). What you're doing is you output every first element of every row.
If you want to output every element in one line, just concatenate the array again:
echo join(';', $line);
But then that's missing the point of fgetcsv, which is specifically helpfully separating those elements into an array for you so you can work with them.
<?php
function aum($x) {
$contents = $_FILES['userfile']['tmp_name'];
$contents = file("$contents");
$aum = $contents[$x][13].$contents[$x][14].$contents[$x][15].$contents[$x][16].$contents[$x][17].$contents[$x][18].$contents[$x][19].$contents[$x][20].$contents[$x][21].$contents[$x][22].$contents[$x][23];
$faum = money_format('%(#1n',$aum)."\n";
return $faum;
}
?>
Notice: A non well formed numeric
value encountered in
./includes.php
on line 28
Hi,
I'm getting the error above. Line 28 is: $faum = money_format('%(#1n',$aum)."\n";
I have three questions:
Why am I getting this error notice and what should I do to fix it?
Is there a better way to upload a CSV text file that has non-uniform comma separation into a HTML table? By "non-uniform" comma separation I mean: KEY DATA,DATA,,,$aum DATA,,,,,,DATA,,etc. As you can see, I am deriving $aum by using the file() function. I then count the number of characters from the right of the beginning of each row to get the fixed character number that corresponds with the $aum DATA. The $x variable corresponds to the row numbers in the file. Then I can return each $aum per row $x. I am new to PHP and would like to know if there is a smarter way to do this.
I appreciate any tips/advice that you might share.
thx,
You need to have a look at $aum as it probably can't be formatted as a number.
Pop
echo $aum;
echo floatval($aum);
Before the error to see what you get. You might need to change the position you're looking at if you're picking up leading or trailing data.
for the second question, fgetcsv is your friend to get data out of CSV files
http://ee.php.net/fgetcsv
For CSV parsing, a hand on approach is to use explode. I try this snippet of code
$string = "a,,b";
$result = explode(",", $string);
echo "<pre>".print_r($result, true)."</pre>";
And the output I get back is:
Array
(
[0] => a
[1] =>
[2] => b
)