Hi I'm using a simple import to CSV script that brings information into an array from a CSV file.
The sample output of the print_r($data) statement is:
Array ( [0] => Array ( [Email,Name,"Message Number","Date Added", ...etc ]) => email#email,com,myname,1001,"10/27/16 9:54pm EDT",... etc ) 1 => Array ( [Email,Name,"Message Number","Date Added",
print_r($data[0])
shows Array ( [Email,Name,"Message Number","Date Added",
I'm trying to isolate the variables but each time I get a null result on the quoted values.
$csv="members.csv";
$importer = new CsvImporter($csv,true);
$data = $importer->get();
echo "<pre>";
$n=0;
$messageNumber = $data[$n]['Message Number'];
What am I doing wrong? It should return '1001' in that variable.
Note: I'm using the class CsvImporter on this page in PhP FgetFSV
Again, what I'm looking for is the definition to isolate an individual variable in an easy way.
Thank you!
Perhaps someone has a simpler way to read a CSV into a PHP Array than using the above class?
In the example given in the php docs for CsvImporter it's changing the default delimiter to \t. Try add ',' as the 3rd param for the class:
$importer = new CsvImporter($csv,true, ',');
Hope this helps!
$csv="members.csv";
$importer = new CsvImporter($csv,true, ',');
$data = $importer->get();
echo "<pre>";
$n=0;
$messageNumber = $data[$n]['Message Number'];
print $messageNumber;
Returns the correct '1001' as expected.
The solution is marked above.Thanks to Ross. Simply changing the $importer = new CsvImporter($csv,true, ','); solved the entire puzzle.
Related
I have a file, in which I saved data in array format and later I want to read this data into a variable and this variable must behave like an array.
Suppose I have a file on my pc : C:/test.txt and it contains an array :
Array
(
[first_name] => John
[last_name] => Doe
[email] => johndoe#gmail.com
)
Now I am fetching this data using below method :
$myfile = fopen("C:/test.txt", "r");
$test = fread($myfile,filesize("C:/test.txt"));
Now when I print $test it shows the data like array but when I check the datatype of this variable then it shows String.
I have also converted this variable into array using type casting :
$test1 = (Array) $test;
But when tried to fetch any index from $test1 then it show Illegal string error.
So can somebody help me out.
Try this
$file = "C:/test.txt";
$document = fopen($file,'r');
$contents = fread($document, filesize($file));
fclose($document);
this will give you a array $contents
print_r($contents);
C:/test.php
<?php
return array(
'first_name' => null,
'last_name' => null,
'email' => 'new',
);
another file:
<?php
$array = inclde('C:/test.php');
Or save json in file C:/test.json
{"first_name":null,"last_name":null,"email":"new"}
and in another file:
<?php
$json = file_get_contents('C:/test.json');
$array = json_decode($json, true);
Do this:
// $myarray is the array
file_put_contents('my_file', serialize($myarray));
// Later ...
$array = unserialize(file_get_contents('my_file'));
You can guess what serialize or unserialize does. But read more in docs to learn more specifically.
#VladimirKovpak 's answer will work too, but for simple arrays. Using serialization, you can save nearly any object, and get it back.
If you need more control over serialization process, look into magic methods __sleep and __wakeup from docs.
I am a bit new to PHP, and I am having some trouble converting a csv file into a multidimensional array, where each dimension has a name. I need to two distinct named array so that I can use them in a preg_replace statement like the below:
$expand_abbrev=preg_replace($contracted_form , $expanded_form , $sentence);
the file content are as follows:
contracted_form,expanded_form
'/a./','in dates ante'
'/abbrev./','abbreviation of'
'/Abbrev./','abbreviations'
'/Abd./','Aberdeen'
'/Aberd./','Aberdeen'
'/Aberdeensh./','Aberdeenshire'
This is so far what I have come up with, but it does not achieve the desired output.
$abbrev_list=file_get_contents('files/abbreviations.text');
$test=str_getcsv($abbrev_list, ",");
$expand_abbrev=preg_replace($contracted_form, $expanded_form, $sentence);
Can anyone help me out with this please ? I have been trying so many times but so far no success.
---- Please allow me to make a clarification, because it seems I might have mislead you. I would like to process a csv file which has two two values per line contracted_form and expanded_form. These two values per line are separated by a comma.
I am not sure how best to approach it, I was thinking perhaps splitting the each line into two arrays like for example each contracted_form is stored in the contracted_from array and each expanded_form is stored in the expanded_form array.
So that preg_replace can replace any instance of contracted_from, encountered in a sentence with its corresponding expanded_form. So for example the following sentence:
Hi sir, I live in a flat in Abd.
So preg_replace(Adb. , Aberdeen, Hi sir, I live in a flat in Abd.) would result in the below.
Hi sir, I live in a flat in Aberdeen.
So from what I understood you want to put each line of the csv into a multi dimensional array, if I understood you wrong please correct me.
Also bare in mind the algorithm below does not take into csv headers into account.
// The Multidimensional Array
$array = array();
$handle = fopen("file.csv", "r");
// If csv if empty, this will not run
while((($data = fgetcsv($handle, null, ',')) !== false)) {
// The "magic" happen here.
temp = array();
$temp["contrated_form"] = $data[0];
$temp["expanded_form"] = $data[1];
array_push($array, $temp);
}
For example if your csv file had the following:
data1,data2
data3,data4
data5,data6
The result of the above algorithm would be:
Array (
[0] => Array (
[contrated_form] => data1
[expanded_form] => data2
)
[1] => Array (
[contrated_form] => data3
[expanded_form] => data4
)
[2] => Array (
[contrated_form] => data5
[expanded_form] => data6
)
)
Tips:
str_getcsv does not know that the first row of your csv file contains your column names.
str_getcsv does not need "," in the statement str_getcsv($abbrev_list, ",") because , is default separator.
Statement $expand_abbrev=... has no idea what you're arguments mean.
You must write a foreach to create array $contracted_form using $test.
You must write a foreach to create array $expanded_form using $test.
I have an array that is filled with different sayings and am trying to output a random one of the sayings. My program prints out the random saying, but sometimes it prints out the variable name that is assigned to the saying instead of the actual saying and I am not sure why.
$foo=Array('saying1', 'saying2', 'saying3');
$foo['saying1'] = "Hello.";
$foo['saying2'] = "World.";
$foo['saying3'] = "Goodbye.";
echo $foo[array_rand($foo)];
So for example it will print World as it should, but other times it will print saying2. Not sure what I am doing wrong.
Drop the values at the start. Change the first line to just:
$foo = array();
What you did was put values 'saying1' and such in the array. You don't want those values in there. You can also drop the index values with:
$foo[] = 'Hello.';
$foo[] = 'World.';
That simplifies your work.
You declared your array in the wrong way on the first line.
If you want to use your array as an associative Array:
$foo=Array('saying1' => array (), 'saying2' => array(), 'saying3' => array());
Or you can go for the not associative style given by Kainaw.
Edit: Calling this on the not associative array:
echo("<pre>"); print_r($foo); echo("</pre>");
Has as output:
Array
(
[0] => saying1
[1] => saying2
[2] => saying3
[saying1] => Hello.
[saying2] => World.
[saying3] => Goodbye.
)
Building on what #Answers_Seeker has said, to get your code to work the way you expect it, you'd have to re-declare and initialise your array using one of the methods below:
$foo=array('saying1'=>'Hello.', 'saying2'=>'World.', 'saying3'=>'Goodbye.');
OR this:
$foo=array();
$foo['saying1'] = "Hello.";
$foo['saying2'] = "World.";
$foo['saying3'] = "Goodbye.";
Then, to print the contents randomly:
echo $foo[array_rand($foo)];
I'm trying to build URL query from an Array that looks like that:
$serials = ['3804689','3801239','3555689','3804687','1404689','6804689','8844689','4104689','2704689','4604689'];
I would like to get query like that:
localhost/get?serial=3804689&serial=3801239&serial=3555689
(you get the idea)
I'm trying to use http_build_query($serials, 'serial', '&'); but it adds the numeric index to the prefix 'serial'.
Any idea how to remove that numeric index?
Well you can't really have the same GET parameter in the string, After all if you try to access that variable server side, what would you use?
$_GET['serial'] - But which serial would it get?
If you really want to get a list of serials, Simply turn the array into a string, save it as an array and there you go. for example :
$serials = "string of serials, delimited by &";
Then you can use the http build query.
Maybe use a foreach:
$get = "localhost/get?serial=" . $serials[0];
unset( $serials[0] );
foreach( $serials AS serial ){
$get .= "&serial=$serial;
}
Just as an FYI, PHP doesn't handle multiple GET variables with the same name natively. You will have to implement something fairly custom. If you are wanting to create a query string with multiple serial numbers, use a delimiter like _ or -.
Ex: soemthing.com/serials.php?serials=09830-20990-91234-12342
To do something like this from an array would be simple
$get_uri = "?serial=" . implode("-", $serials);
You would be able to get the array back from a the string using an explode to
$serials = explode("-", $_GET['serials']);
Yes its quite possible to have such format, you have to build it query string by indices. Like this:
No need to build the query string by hand, use http_build_query() in this case:
$serials = ['3804689','3801239','3555689','3804687','1404689','6804689','8844689','4104689','2704689','4604689'];
$temp = $serials;
unset($serials);
$serials['serial'] = $temp;
$query_string = http_build_query($serials);
echo urldecode($query_string);
// serial[0]=3804689&serial[1]=3801239&serial[2]=3555689&serial[3]=3804687&serial[4]=1404689&serial[5]=6804689&serial[6]=8844689&serial[7]=4104689&serial[8]=2704689&serial[9]=4604689
And then finally, if you need to process it somewhere, just access it thru $_GET['serial'];
$serials = $_GET['serial']; // this will now hold an array of serials
You can also try this
$get = "localhost/get?serial=";
$serials = ['3804689','3801239','3555689','3804687','1404689','6804689','8844689','4104689','2704689','4604689'];
$list = implode("&serial=",$serials);
echo $get.$list;
Having the same GET parameter will not work this way. You will need to use an array in the get parameter:
localhost/get?serial[]=3804689&serial[]=3801239&serial[]=3555689
IF you just print $_GET through this URL, you will receive
Array ( [serial] => Array ( [0] => 380468 [1] => 3801239 [2]=> 3555689) )
Then you can do this to build your query string
$query_str = 'serial[]='.implode('&serials[]=',$serials);
You can try this version.
$serials = ['3804689','3801239','3555689','3804687','1404689','6804689','8844689','4104689','2704689','4604689'];
$get = implode('&serials[]=',$serials);
echo 'test';
var_dump($_GET['serials']);
Result
I am generating an php array and then converting it to a xml playlist. converting array to xml is no problem, but i am having problem generating the array. I am getting data from DB and want to use it. My code is like bellow-
$songs2008 = get_data("musics", "where year='2008'");
$mysongs = array();
foreach($songs2008 as $k1=>$v1){
$entry = array(
"url"=>"songs/main_songs/".$v1[file_name],
"songname"=>$v1[song_title],
"artist"=>$v1[artist]
);
array_push($mysongs, $entry);
}
and the array is -
$array = array(
"settings"=>array(
"width"=>"316",
"songs"=>array(
"albumArt"=>array(
"url"=>"songs/2008.jpg",
"entries"=>array(
"entry"=>$mysongs['0'],
"entry"=>$mysongs['1'],
"entry"=>$mysongs['2'],
----------------------
----------------------
)
)
)
);
Its not working at the entries. the array key is same(entry); so only one showing. is there any solution? any other way to do it? please help.
It's because you can't use 'entry' as an index more than once. Try:
"entries" => $mysongs
#see: http://php.net/manual/de/language.types.array.php for further reading an php arrays
But be carefull, you'll propably be running into some problems creating your xml code when using this. For I would bet that you are using the array keys as tag names!
Don't name your array key for "entry"
$array = array(
"settings"=>array(
"width"=>"316",
"songs"=>array(
"albumArt"=>array(
"url"=>"songs/2008.jpg",
"entries"=>array(
$mysongs['0'],
$mysongs['1'],
$mysongs['2'],
----------------------
----------------------
)
)
)
);