php explode() storing all values from test filt to index [0] - php

I am a student, currently learning PHP and having a tough time getting the explode() function to work the way I want.
The following text file "vacations.txt" contains:
"54321", "Big Island Hawaii", "2999.00", "Best beaches big volcano"
"87654", "Cruise Caribbean", "3500.00", "Ocean view with balcony Cancun Jamaica etc."
"09876", "Rome and Madrid", "3999.00", "I see Italy I see Spain"
"32198", "Ski Tahoe", "1200.00", "Ski all day Gamble all night"
I have tried to put this into an array delimited by the comma. Using print_r(), I can see that it's all going into the first index of my array.
Here's my code:
function displaySpecials() {
$prodString = include("vacation.txt");
$vacArray = explode(',', $prodString );
print_r($vacArray);
}
Here is the output:
"54321", "Big Island Hawaii", "2999.00", "Best beaches big volcano"
"87654", "Cruise Caribbean", "3500.00", "Ocean view with balcony
Cancun Jamaica etc." "09876", "Rome and Madrid", "3999.00", "I see
Italy I see Spain" "32198", "Ski Tahoe", "1200.00", "Ski all day
Gamble all night"Array ( [0] => 1 )
I have searched, and read everything I can find about explode(), but I cannot figure out why this is happening. My end goal is to output a multidimentional array in a table with 4 rows and 4 columns to display the 16 values in the text file.
All help is greatly appreciated. Thank you in advance!

The include statement includes and evaluates the specified file.
include will evaluate whatever is in it, basically to include other php script.
You need to fetch its content.
Below I have used file to fetch contents of file linewise.
function displaySpecials() {
$lines = file("vacation.txt"); // will return lines in array
foreach($lines as $line){ // loop for each line
$vacArray[] = explode(",", $line); // insert resulting array to last index of $varArray
}
print_r($vacArray);
return $vacArray;
}
Also, the file appears to be regular .csv you can use fgetcsv. Check the example in the official docs.

Since this is basically a csv file, I'd recommend using fgetcsv, something like this:
if (($h = fopen('vacation.txt', 'r')) !== false) {
while (($data = fgetcsv($h, 1000, ',')) !== false) {
// Fetch the data here
}
}
Optionally, you can also use str_getcsv:
$data = array_map('str_getcsv', file('vacation.txt'));

Try to replace include("vacation.txt") with file_get_contents("vacation.txt").
include
The include statement includes and evaluates the specified file.
file_get contents
Reads entire file into a string
Your code should look like this:
function displaySpecials() {
$prodString = file_get_contents("vacation.txt");
$vacArray = explode(',', $prodString );
print_r($vacArray);
}

Related

How do I put a .csv file correctly into an array in PHP?

So I'd like to make a basic login/register page. I got a CSV file which roughly looks like this:
a, b
r,d
login, pass
I am already able to correctly add new combinations to the file. But if I want to put the CSV into an array so that I can check if the username/password combination is true, I only get the first row in the array, so [0] = "a" and [1] = "b". There are similar questions on this site on how to put a csv into an array, but with every solution this problem comes up. How do I get the other elements in the array, too?
Edit: as suggested, the code I used:
$database = fopen("database.csv", "r");
$data = fgetcsv($database, 1000, ",");
print_r($data);
This returns: Array ( [0] => q [1] => w )
Exact data:
q,w
g,h
o,p
t,y
c,d
o,p
o,p
a,b
Hope you can help me.
You can see from the documentation that fgetcsv returns just one line from the file pointer, and NULL or FALSE if it was unable to get another line.
You should put your code in a while loop to get all of the CSV rows.
$credentials = array();
$database = fopen("database.csv", "r");
while (is_array($data = fgetcsv($database, 1000, ','))) {
$credentials[] = $data;
}
fclose($database);
var_dump($credentials); // This contains all of the credentials.

PHP fgetcsv 2 dimensional array

I have seen few similar examples but it is still not working.
csv data file "data1.csv" is as below:
symbol,num1,num2
QCOM,10,100
QCOM,20,200
QCOM,30,300
QCOM,40,400
CTSH,10,111
CTSH,20,222
CTSH,30,333
CTSH,40,444
AAPL,10,11
AAPL,20,22
AAPL,30,33
AAPL,40,44
--end of file ----
$inputsymbol = QCOM ; // $inputsymbol will come from html.works fine.
I want to read the csv file and fetch lines that matches symbol = QCOM. and convert it in to array $data1 to plot line chart for num1 and num2 as below.
$data1 = array (
array(10,100),
array(20,200),
array(30,300),
array(40,400)
);
Note: 1. no comma at the end of each csv lines in csv datafile.
2. Multiple symbols in same file. so the lines that match symbols only
should be included in $data1.
==============
Mark's soluition solves the problem. Now to make the data access faster (for a very large csv file), I have (externally) formatted same data as below. Question is how it can automatically extract headers and then for the data1 array?
symbol,1/1/2015,1/2/2015,1/3/2015,1/4/2015
QCOM,100,200,300,400
CTSH,11,22,33,44
AAPL,10,11,12,13
Note that the number of fields in header is not fixed. (it will increase every month). But the data will also increse accordingly.
Not complicated:
$inputsymbol = 'QCOM';
$data1 = [];
$fh = fopen("data1.csv", "r"));
while (($data = fgetcsv($fh, 1024)) !== FALSE) {
if ($data[0] == $inputsymbol) {
unset($data[0]);
$data1[] = $data;
}
}
fclose($fh);
So where exactly are you having the problem?

Searching a text file and displaying a part of the String. (PHP)

So I want to search a text file which contains a list of suburbs with names and postcodes. Depending on the the postcode given I want to display the suburb. I know I'm suppose to loop through the text file but have no idea how to actually search for exact value in the line and then display a different part of that same line. I know that I can use the explode function and get the part of the string I want but what I don't know how to do is loop through the file and finding the exact line of it.
Any Help on this is most Appreciated !
Thanks !
Since you didn't provide any example of what you have tried so far, this may not completely match what you are doing.
Assuming a file suburbs.txt with contents like:
Somewhere,12345
Somewhere Else,12346
This Place,12347
There,12348
You could do the following to loop through the entries:
$zipCode = '12346';
$lines = file('/path/to/suburbs.txt');
foreach ( $lines as $line )
{
$fields = explode( ',', $line );
if ( $fields[1] == $zipCode )
{
echo "Your suburb is: " . $fields[0];
break;
}
}
file() loads a file into an array. This is what allows you to loop through using foreach(). There are other methods of doing this as well, but this should help you move in the right direction.

Preg-Match-All - Synonym File

I am writing a php script that will parse through a file, (synonyms.dat), and coordinate a list of synonyms with their parent word, for about 150k words.
Example from file:
1|2
(adj)|one|i|ane|cardinal
(noun)|one|I|ace|single|unity|digit|figure
1-dodecanol|1
(noun)|lauryl alcohol|alcohol
1-hitter|1
(noun)|one-hitter|baseball|baseball game|ball
10|2
(adj)|ten|x|cardinal
(noun)|ten|X|tenner|decade|large integer
100|2
(adj)|hundred|a hundred|one hundred|c|cardinal
(noun)|hundred|C|century|one C|centred|large integer
1000|2
(adj)|thousand|a thousand|one thousand|m|k|cardinal
(noun)|thousand|one thousand|M|K|chiliad|G|grand|thou|yard|large integer
**10000|1
(noun)|ten thousand|myriad|large**
In the example above I want to link ten thousand, myriad, large to the word 1000.
I have tried various method of reading the .dat file into memory using file_get_contents and then exploding the file at \n, and using various array search techniques to find the 'parent' word and it's synonyms. However, this is extremely slow, and more often then not crashes my web server.
I believe what I need to do is use preg_match_all to explode the string, and then just iterate over the string, inserting into my database where appropriate.
$contents = file_get_contents($page);
preg_match_all("/([^\s]+)\|[0-9].*/",$contents,$out, PREG_SET_ORDER);
This matches each
1|2
1-dodecanol|1
1-hitter|1
But I don't know how to link the fields in between each match, IE the synonyms themselves.
This script is intended to be run once, to get all the information into my database appropriately. For those interested, I have a database 'synonym_index' which holds a unique id of each word, as well as the word. Then another table 'synonym_listing' which contains a 'word_id' column and a 'synomym_id' column where each column is a foreign key to synonym_index. There can be multiple synonym_id's to each word_id.
Your help is greatly appreciated!
You can use explode() to split each line into fields. (Or, depending on the precise format of the input, fgetcsv() might be a better choice.)
Illustrative example, which will almost certainly need adjustment for your specific use case and data format:
$infile = fopen('synonyms.dat', 'r');
while (!feof($infile)) {
$line = rtrim(fgets($infile), "\r\n");
if ( $line === '' ) {
continue;
}
// Line follows the format HEAD_WORD|NUMBER_OF_SYNONYM_LINES
list($headWord, $n) = explode('|', $line);
$synonyms = array();
// For each synonym line...
while ( $n-- ) {
$line = rtrim(fgets($infile), "\r\n");
$fields = explode('|', $line);
$partOfSpeech = substr(array_shift($fields), 1, -1);
$synonyms[$partOfSpeech] = $fields;
}
// Now here, when $headWord is '**10000', $synonyms should be array(
// 'noun' => array('ten thousand', 'myriad', 'large**')
// )
}
Wow, for this type of functionality you have databases with tables and indices.
PHP is to serve a request/response, not to read a big file into memory. I advise you to put the data in a database. That will be much faster - and it is made for it.

PHP: Taking Array (CSV) And Intelligently Returning Information

Hey Everyone. I'm a first time poster, but I've browsed this site a number of times. I have a coding issue that I'm not sure exactly how to solve. First I'll explain what I need to do, and what information I have, and I hope somebody can give me a nudge in the right direction.
What I have is a spreadsheet (CSV) that has the following info: Zone Name, Zip Code, City Name. One zone should have many cities that fall under it, and every city most likely has many zip codes that fall under it. For example:
Zone H, 92603, Irvine
Zone H, 92604, Irvine
Zone J, 92625, Corona
etc.
Okay, now that that's out of the way, here's what I need to do with this info. I need to be able to input a city name and have it return to me all zip codes that fall under that city, as well as the zone that the city lies in. For example, if I input Chatsworth, it should give me (Zone X) and (12345, 12346, 12347) as the zip codes (just an example).
I'm not sure the best way to go about this. I could create a MySQL database and work from there, or just work from .csv files, or hardcode it into the PHP file. I don't know how to search for a value in an array column, and then return the other columns accordingly (especially with multiple zip codes per city).
If anybody can help me out, it would be greatly appreciated. Also, feel free to let me know if you need more information from me. Thanks in advance to everyone reading.
If you want to pursue the CSV approach, then the first step is reading the file into a 2D array:
$csv = array_map("str_getcsv", file("file.csv"));
Now this is an indexed array, where you need to know which column is which. But if you know the city is always in [2] then searching for the other information becomes simple:
foreach ($csv as $i=>$row) {
if ($row[2] == "Chatsworth") {
$zone = $row[0];
$zip = $row[1];
break;
}
}
Ideally you would put this into a function, so you can call it multiple times. It would be easiest if you make it configurable which column to search, and just have it return the complete found row.
Okay so if you don't know where the $city name is in, then I would propose following utility function:
function search_csv($city) {
global $csv; // pre-parsed array (can be parameter though)
foreach ($csv as $i=>$row) {
if (in_array($city, $row)) {
$result_rows[] = $row;
}
}
return $result_rows;
}
function search_zip($city) {
$rows = search_csv($city);
foreach ($rows as $i=>$row) {
$rows[$i] = end(array_filter($row, "is_numeric"));
}
return $rows;
}
The first one returns a list of $rows which match. I'll leave it up to you how to figure out which column contains which. Only for the zip code it's kind of possible to return the results deterministically.
Zone H, 92603, Irvine
Zone H, 92604, Irvine
Zone J, 92625, Corona
etc.
you can take the file and get all its contents. then split it up by new line:
$searchCity = 'Searched'; //or whatever city you are looking for
$file = file_get_contents('file.csv');
$results = array();
$lines = explode("\n",$file);
//use any line delim as the 1st param,
//im deciding on \n but idk how your file is encoded
foreach($lines as $line){
//split the line
$col = explode(",",$line);
//and you know city is the 3rd element
if(trim($col[2]) == $searchCity){
$results[] = $col;
}
}
and at the end u have an array of the results like this:
$results = array(
array('Zone B', '12345', 'Searched'),
array('Zone Z', '35145', 'Searched'),
array('Zone Q', '12365', 'Searched'),
)

Categories