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]);
}
Related
This question already has answers here:
How to extract data from csv file in PHP
(13 answers)
Closed 1 year ago.
Apologies if this question is close to others. I have tried every solution to accomplish something simple with nothing but failure. :-(
I want the keys from array one to be assigned as keys to array two.
$demos_keys = array_keys($demos);
//$c = array_combine($demos_keys, $csvdata); produces "FALSE"
//$c = $demos_keys + $csvdata; simply adds the arrays but doesn't assign keys
So then I tried to loop through each element to assign the keys manually - to no avail!
foreach ($csvdata as $row){
for($i = 0; $i<count($demo_keys); $i++) {
$csvdata[$demo_keys[$i]]=$row[$i];
}
}
demos_keys:
lastname":"lastname","email":"email","d1":"phone","d2":"status"
csvdata:
"Dryer,fdryer#email.com,Backfield,North\r","Harris,fharris#email.com,Corp,South\r",etc.
I feel the csvdata array is wonky somehow. Every thing say it is an array with about 1000 rows, but the carriage return at the end of the last element is troubling me. I thought I'd deal with it later.
What else can I try!? Thank you all for any contributions!
It looks like each row of your CSV data has not been parsed into separate variables (are you reading it from a file using fgets or file instead of fgetcsv?). So you need to split it before you can combine it with the keys from $demos_keys. Something like this should work:
$demos_keys = array("lastname","email","d1","d2");
$csvdata = array("Dryer,fdryer#email.com,Backfield,North\r","Harris,fharris#email.com,Corp,South\r");
$result = array();
foreach ($csvdata as $row) {
$data = explode(',', trim($row));
$result[] = array_combine($demos_keys, $data);
}
print_r($result);
Output:
Array
(
[0] => Array
(
[lastname] => Dryer
[email] => fdryer#email.com
[d1] => Backfield
[d2] => North
)
[1] => Array
(
[lastname] => Harris
[email] => fharris#email.com
[d1] => Corp
[d2] => South
)
)
Demo on 3v4l.org
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,
I am trying to program a web crawler but I have no idea, how to create a recursion for parsing a webpage and adding all the endresults into a final array.
I never worked with php before but I did alot of research on the internet and figured already out, how to parse the page I want to scrape.
Please note, that I have changed the $url value and the array result below to some values which I have randomly generated in my mind.
<?php
include_once "simple_html_dom.php"; //http://simplehtmldom.sourceforge.net/
$url = "https://www.scrapesite.com/pagetoscrape/index.html";
function parseLink($link) {
$html = file_get_html($link);
$html = $html->find("/html/body/script[2]/text", 0);
preg_match('/\{(?:[^{}]|(?R))*\}/', $html, $matches); //this regex extracts a json array
$json = json_decode($matches[0]);
$data = ($json->props->contents);
return $data;
}
function getFolders($basepath, $data) {
$data = $data->folders;
$result = array();
foreach ($data as $value) {
$result[] = array("folder", $basepath . "/" . $value->filename, $value->href);
}
return $result;
}
$data = getFolders("", parseLink($url));
print_r ($data);
?>
This script works fine and it outputs the following:
Array
(
[0] => Array
(
[0] => folder
[1] => /1
[2] => https://www.scrapesite.com/pagetoscrape/sjdfi327943sad/index.html
)
[1] => Array
(
[0] => folder
[1] => /2
[2] => https://www.scrapesite.com/pagetoscrape/345fdsjjsdfsdf/index.html
)
[2] => Array
(
[0] => folder
[1] => /3
[2] => https://www.scrapesite.com/pagetoscrape/46589dsjodsiods/index.html
)
[3] => Array
(
[0] => folder
[1] => /4
[2] => https://www.scrapesite.com/pagetoscrape/345897dujfosfsd/index.html
)
[4] => Array
(
[0] => folder
[1] => /5
[2] => https://www.scrapesite.com/pagetoscrape/9dsfghshdfsds3/index.html
)
)
Now, the script should execute the getFolders function for every item in the above array. This may return another array of folder which should get parsed too.
And then I want to create a final array where all the folders ABSOLUTE paths ($basepath . "/" . $value->filename) and href links are listed. I really appreciate every little hint.
I was able to find some example on the web but I can't figure out how to implement it here because I have almost no experience with programming languages in general.
Initialize an empty array and pass that as a reference to the getFolders() function. Keep putting the results of scraping inside this array. Also, you need to call getFolders() again inside the foreach loop of the getFolders(). Example below:
$finalResults = array();
getFolders("", parseLink($url), $finalResults);
Your getFolders() function signature will now look like below:
function getFolders($basepath, $data, &$finalResults) //notice the & before the $finalResults used for passing by reference
And, your foreach loop:
foreach ($data as $value) {
$finalResults[] = array("folder", $basepath . "/" . $value->filename, $value->href);
getFolders("", parseLink($value->href), $finalResults);
}
Above code is just an example. Change it according to your needs.
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
Example :
Array
(
[0] => "example.fr", "2013-08-24", "test"
[1] => "toto.com, "2014-10-01", "test2"
)
How can I do to split this array every comma ? I would like to get every word in quotes into a variable like this :
$var1= "example.fr";
$var2= "2013-08-24";
$var3 = "test";
....
EDIT: The structure of the array is GOOD ! Every element is enclosed in quotes in ONLY one array ! Like CSV file
Don't reinvent a CSV parser, use the existing functionality.
From PHP 5.3+:
$parsed = array_map('str_getcsv', $array);
http://php.net/str_getcsv
Before 5.3:
$fh = fopen('php://temp', 'r+');
$parsed = array();
foreach ($array as $row) {
ftruncate($fh, 0);
fwrite($fh, $row);
rewind($fh);
$parsed[] = fgetcsv($fh);
}
fclose($fh);
You can use list
array("example.fr, 2013-08-24, test")
list($var1, $var2, $var3) = explode(', ', $array[0]); // or current
Unless I'm misunderstanding you, you can access the array elements and assign them to variables like this:
$var1 = $arrayName[0][0];
$var2 = $arrayName[0][1];
$var3 = $arrayName[0][2];
I can't tell from you're question if the array is holding a single string per index or if it is a 2D array. If it's holding strings then see realshadow's answer.
Use explode on every item of the array: http://www.w3schools.com/php/func_string_explode.asp
I don't think your syntax is quite right to create a multidimensional array, consider this example:
$myArray = array( array("example.fr", "2013-08-24", "test"),
array("toto.com, "2014-10-01", "test2"));
Now you have an array of arrays and can iterate over each.
If you know for sure how many items you have in each array then you can explode the array into its constituents, but if you don't know before hand than iterating will see you through.
I am not very sure with the structure, but let me know if this is what ur looking for, happy to help u then -
<?php
$myarr = array( array("example.fr", "2013-08-24", "test"),array("toto.com", "2014-10-01", "test2"));
foreach($myarr as $breakpart)
{
echo "<pre>";
print_r($breakpart);
}
OUTPUT -
Array
(
[0] => example.fr
[1] => 2013-08-24
[2] => test
)
Array
(
[0] => toto.com
[1] => 2014-10-01
[2] => test2
)
Codepad Link - codepad.org/6S7EMldq