Slistryko Slistryko - 3 months ago 9
JSON Question

Get properly info out from txt file

I'm using php to grab some information from a text file.
But i cant get my array to grab the correct information.

this is essentially the contents of the text-file:

FIRSTNAME=firstname
NAME=lastname
STREET=street adress
CITY=cityname
ZIP=zipcode
COUNTRY=country
ISOCOUNTRY=US
EMAIL=email@domene.com
MOBILENO=123456789
USERNO=somenumber



[PRODUCT]
QTY=2
ALPROJECTID=1123208
PRICE=134,00
DESCRIPTION=product1
ARTNO=1


[PRODUCT]

QTY=1
ALPROJECTID=1123208
PRICE=134,00
DESCRIPTION=product1
ARTNO=1


is there a way to output the second product as 2 products?

this is the code i have written:

$articles = array();

//foreach( $articles as $article ){
$prodno = (int)$lines['ARTNO'];
$prodno = $artkobling[$prodno];

$articles['theproduct'][$prodno][$projectid] = array(
'prodno' => $prodno,
'quantity' => $lines['QTY'],
'product' => $lines['TYPE'],
'product' => $lines['TYPE'],
'referenceid' => $lines['ORDERID'],
'refid' => $lines['CUSTOMERID'],
'unitprice' => (int)$lines['PRICE']
);


$orderdata = array(
'userid' => $this->account,
'fullname' => $lines['FIRSTNAME'] . " " . $lines['NAME'] ,
'address' => $lines['STREET'],
'zipcode' => $lines['ZIP'],
'city' => $lines['CITY'],
'article' => $articles,
'comment' => $lines['CUSTOMERID'] . " " . $lines['ORDERID'] ,
);


When im debugging this it works as expected and gets the result from one product. But how can i get the results as 2 products. I am not sure if i explained the problem good enough. It would have been easier if the file was JSON or XML and not the txt format.

Answer

I would use parse_ini_string to transform the text file into a data structure.

//read the file contents
$raw = file_get_contents('/path/to/textfile.txt');

//replace [PRODUCT] with [PRODUCT_0], [PRODUCT_1]...    
$raw = preg_replace_callback(
    '/\[PRODUCT\]/',
    function() {static $i=0; return '[PRODUCT_'.$i++.']';}
    ,$raw, -1, $count);

//parse raw string into an array
$data = parse_ini_string($raw,true);

//extract the products into their own array. This assumes that
//[PRODUCT] sections are always at the end of the file
$products = array_values(array_splice($data,$count*-1));

//Build the final array
$data = $data + ['PRODUCTS'=>$products];

This will transform your text file into a $data array that has a key for each property, and all products in their own array under the key PRODUCTS.

Live demo

As a bonus, $count is the number of products. From there you can do what you want with the data.