Reading from text file into multidimentional array - php

I have this file that I would like to read into a multidimenstional array in php: file. If I take the first set of lines as a first example, I would like the print_r to look something like this:
Array
(
[SiiNunit] => Array
(
[0] => Array
(
[economy] => _nameless.2BB8.4FB8
[economy_data] => Array
[0] => Array
(
[bank] = _nameless.2917.43B0
[player] = _nameless.2813.6928
[companies] = 312
[companies[0]] = company.volatile.euroacres.nurnberg
[companies[1]] = company.volatile.euroacres.erfurt
etc...
Then as another example, further down the file when it is listing all of the jobs like this:
job_offer_data : _nameless.2BD0.8940 {
cargo: null
company_truck: ""
variant: nil
target: ""
expiration_time: nil
urgency: nil
shortest_distance_km: 0
ferry_time: 0
ferry_price: 0
trailer_pos: (0, 0, 0) (1; 0, 0, 0)
trailer_pos_valid: false
license_plate: ""
}
I would like the array to look somethink like this:
[job_offer] => _nameless.2BB8.4FB8
[job_offer_data] => Array
(
[0] => Array
(
[cargo] = null
[company_truck] = ""
[variant] = nill
[target] = ""
etc...
My code at the moment is:
<?php
// Open the file
$fp = #fopen("game.sii", 'r');
// Add each line to an array
if ($fp) {
$array = explode("\n", fread($fp, filesize("game.sii")));
}
print_r($array);
?>
this (as I expected it to) wrote each line of the file into a 1d array however, I would like it to write it to a multidimensional array=.
Even after lots of googling, I just cannot find the solution for how to do this (so I apologise if I have missed something obvious) so I was hoping someone on here could help me.
Thanks in advance,
Marcus

use serialize php function to before write data to the file the write it to the file
and use unserialize php after read data from file
ex :
$str = serialize($array); //then write it to file
$arr = unserialize($str); //after read from file

Related

Import CSV file into array

Thank you for the response. I will give it a try and update my question, I have my own code but it is a bit messy to show all. My problem is that I do not get the indexes right.
I use:
$products = array();
$lines = file('data_stock.csv', FILE_IGNORE_NEW_LINES);
foreach ($lines as $key => $value)
{
$products[$key] = str_getcsv($value);
}
And I manage to read the data, but this will give me an error:
if ((int)$products[$_sku] > 0 && isset($products[$_sku])) {
Error: Notice: Undefined index: test-product-1 in....
The 'test-product-1' is from the sku column in the csv file
Output from
echo '<pre>';
print_r($products);
echo '</pre>';
gives:
Array
(
[0] => Array
(
[0] => sku
[1] => qty
)
[1] => Array
(
[0] => test-product-1
[1] => 3
)
[2] => Array
(
[0] => test-product-2
[1] => 6
)
[3] => Array
(
[0] => test-product-3
[1] => 30
)
)
I am trying to use a csv file to be imported into the array to replace
$products = [
'test-product-1' => 3,
'test-product-2' => 6,
'test-product-3' => 30
];
But I can not produce the same array when I import from the CSV file, which will cause problems. Examples for CSV to array: http://php.net/manual/en/function.str-getcsv.php
CSV file:
sku,qty
test-product-1,3
test-product-2,6
test-product-3,30
Next step is to extend the script to handle prices. I need to be able to pick up these variables from the CSV file too. And use them inside the for loop.
sku,qty,price,special_price
test-product-1,3,100,50
test-product-2,6,99,
test-product-3,30,500,300
I think the problem is that when you store the row, your storing it indexed by the row number ($key will be the line number in the file). Instead I think you want to index it by the first column of the CSV file. So extract the data first (using str_getcsv() as you do already) and index by the first column ([0])...
$products = array();
$lines = file('data_stock.csv', FILE_IGNORE_NEW_LINES);
foreach ($lines as $value)
{
$data = str_getcsv($value);
$products[$data[0]] = $data;
}
If you want to add the first row as a header and use it to key the data...
$products = array();
$lines = file('data_stock.csv', FILE_IGNORE_NEW_LINES);
$headers = str_getcsv(array_shift($lines));
$products = array();
foreach ( $lines as $value ) {
$data = str_getcsv($value);
$products[$data[0]] = array_combine($headers, $data);
}
The removes the first row of the array using array_shift() and then uses this row in the array_combine() as the keys for each row. With your test data, you would get something like...
Array
(
[test-product-1] => Array
(
[sku] => test-product-1
[qty] => 3
[price] => 100
[special_price] => 50
)
I used following code in my project and its working fine for me.
I used csv_reader PHP library for it.
You have to put this library in your library folder and import it into file where you want to read your csv.
include_once('../csv_reader.php');
$read = new CSV_Reader;
$read->strFilePath = "file_name_with_path";
$read->strOutPutMode = 0; // 1 will show as HTML 0 will return an array
$read->setDefaultConfiguration();
$read->readTheCsv();
$dataArr = array();
$dataArr = $read->arrOutPut;
In $dataArr, i will get the result,

Creating a PHP array from the contents of a file

I have a php file that contains text in the following format.
line 1 - "Title","URL","imgURL","tags"
line 2 - "Title","URL","imgURL","tags"
line 3 - "Title","URL","imgURL","tags"
It is basically structured like a database so each line is a record and 1st set of "" is always a title. 2nd set of "" is always a URL, etc.... line by line.
I'm not an experienced programmer by any stretch of the imagination. What is the best way to create an array from the contents of the file?
I've tried the following, but it didn't work.
$content = array(file_get_contents("path/content.php"));
I believe I need to update the structure of the data and the method I use to create the array, but I'm not sure how. Any help is greatly appreciated.
I want to be able to retrieve title, URL, imgURL, or tags from any line of text, but I don't know how to express that in an array format.
I think I want to be able to request $content[0][1] to get the URL from line1 and $content[1][3] to get the tags from line2.
$file = fopen("path/content.php", "r");
while($content[] = fgetcsv($file, 1000, ","));
You should then be able to access each element as you specified:
echo $content[0][1]; // echos first line, url
The format of your file is called CSV (comma separated values). Using PHP, you can parse a CSV file using the function fgetcsv: http://php.net/manual/en/function.fgetcsv.php
Are you looking for something like this?
/**
* Decodes a full CSV file to an array.
*
* #param string $file File to decode
*
* #throws \Exception
*
* #return array[]
*/
function csv_decode($file) {
$fh = fopen($file, 'r');
if($fh === false)
{
// FIXME: You should replace this with your own exception!
throw new \Exception("Failed to open file '$file' for reading");
}
$rows = [];
while ($row = fgetcsv($fh))
{
$rows[] = $row;
}
return $rows;
}
The format you have encountered is known as CSV (which stands for comma-separated values)
The above function decodes your data to an array with the structure you've described as can be seen from the output of the following snippet when run on your example data:
print_r(csv_decode('values.txt'));
Which outputs:
Array
(
[0] => Array
(
[0] => Title
[1] => URL
[2] => imgURL
[3] => tags
)
[1] => Array
(
[0] => Title
[1] => URL
[2] => imgURL
[3] => tags
)
[2] => Array
(
[0] => Title
[1] => URL
[2] => imgURL
[3] => tags
)
)

php csv to array

I am fairly new to php and got this from a stack overflow question and cant seem to get it to work for me.
<?php
if (($handle = fopen("fullbox.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
echo "<pre>".print_r($data)." <br /></pre>";
}
fclose($handle);
}
echo $data[1];
?>
I need to set up a couple arrays for pricing using a large number of products(which I can pull from my csv file) Fullbox.csv consists of just 10 numbers with 2 decial places. I have just been trying to test this and this is the output that I get:
Array
(
[0] => 8.53
)
Array
(
[0] => 4.74
)
Array
(
[0] => 5.00
)
Array
(
[0] => 2.50
)
Array
(
[0] => 6.48
)
Array
(
[0] => 3.99
)
Array
(
[0] => 8.53
)
Array
(
[0] => 4.74
)
Array
(
[0] => 8.53
)
Array
(
[0] => 4.74
)
Why is the array setting all values in the [0} place holder of the array and also why is there a 1 in between each line. Thanks in advance.
Update If this is a ten item array this should then return the value of the 1 entry in the array but it doesn't. I essentially just need to store all of the prices so I can use them as variables later. I don't need them to be printed. Thanks again.
echo $data[1];
print_r does not return the formatted array by default; it outputs it and returns 1. Pass true as a second parameter.
echo "<pre>".print_r($data, true)." <br /></pre>";
All the values are in the 0 index of the array because arrays start at 0. There is nothing wrong there.
Try this:
$f = fopen(yourfile, "r");
$fs = filesize(yourfile);
$content = fread($f, $fs);
$lines = explode("\n", $content);
$result = array();
foreach($lines as $line) $result[] = explode(",", $line);
CSV as in Comma Seperated-Values is an array each line. So each line -even if it has only 1 value- is array.
Also you don't need to echo "print_r".
you also read the data from the CSV using the following function and sort using the usort() function.
http://www.pearlbells.co.uk/how-to-sort-a1a2-z9z10aa1aa2-az9az10-using-php/
Read data from the CSV
function readCSV() {
$csv = array_map('str_getcsv', file('data.csv'));
array_shift($csv); //remove headers
$csvData = splitandSort($csv);
createCSV($csvData);
}

getting null values while reading from csv file

I have a csv file which has a word for each row like this
word1
word2
word3
And have the following code to read the data:
$arr = array();
$fh = fopen('path/to/file', 'r');
while (($rows = fgetcsv($fh)) !== false) {
print_r($rows);
if (!in_array($rows[0], $arr))
$arr[] = "'".trim($rows[0])."'";
}
fclose($fh);
print_r($arr);
The problem is im getting empty strings/null for $rows[0] and im quite sure the data is there.
Array ( [0] => )
Array ( [0] => )
Array ( [0] => )
Array ( [0] => '' [1] => '' [2] => '' [3] => '' )
Any help would be greatly appreciated.
You're trying to read the words into an array? Replace all that with just:
$arr = file('/path/to/file');
print_r($arr);
Cannot reproduce. I'm assuming there is something wrong with your file format. Most likely there is an empty line on top (which I'm not quite sure, but might fail the !== false test).
Better try:
$arr = array_map("str_getcsv", file("words.csv"));
print_r($arr);
And if you need to re-add the quotes, do a separate loop.
The file reading part has already been answered, but about your loop to add the quotes, you could use array_walk():
function add_quotes(&$item)
{
$item = "'" . $item . "'";
}
array_walk($arr, "add_quotes");

PHP: reading config.ini to array with file()

My config file looks like this:
title = myTitle;
otherTitle = myOtherTitle;
when I read the file with file(), it creates this array
[0] => title = myTitle;
[1] => otherTitle = myOtherTitle;
and what I want the array to look like is
[title] => myTitle;
[otherTitle] => myOtherTitle;
Am I using the wrong approach her? Should i just read the entire config into a sting and explode it from there?
You can use the parse_ini_file function. It's available in PHP 4 and 5.
If your config file looks like this:
one = 1;
five = 5;
animal = BIRD;
The function will return the following associative array:
Array
(
[one] => 1
[five] => 5
[animal] => BIRD
)
I would just loop through the file and explode each line individually. Here's a simple example, after which you'll end up with $config holding all of your data as requested.
$config = array();
$lines = file("config.ini");
foreach ($lines as $line) {
$vals = explode('=', $line, 2);
$config[trim($vals[0])] = trim($vals[1]);
}

Categories