Read CSV File and Store Data In XML File - php

Hello i have This code
<?php
error_reporting(0);
function csv_to_array($filename='', $delimiter=';')
{
if(!file_exists($filename) || !is_readable($filename))
return FALSE;
$header = NULL;
$data = array();
if (($handle = fopen($filename, 'r')) !== FALSE)
{
while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
{
if(!$header)
$header = $row;
else
$data[] = array_combine($header, $row);
}
fclose($handle);
}
return $data;
}
$csvFile = "example.csv";
$csv = csv_to_array($csvFile);
echo '<pre>';
print_r($csv);
echo '</pre>';
$xml = new DOMDocument("1.0");
$root = $xml->createElement("CATEGORY");
$domAttribute = $xml->createAttribute('name');
// Value for the created attribute
$domAttribute->value = 'Clear Skin 100ml Massage Oil 100ml-massage-oils';
// Don't forget to append it to the element
$root->appendChild($domAttribute);
$xml->appendChild($root);
foreach ($csv as $key => $value) {
$book = $xml->createElement("PRODUCT");
foreach ($value as $key => $value) {
echo $key. " ==> " . $value."<br>";
$key = $xml->createElement($key);
$value = $xml->createTextNode($value);
$key->appendChild($value);
$book->appendChild($key);
}
$root->appendChild($book);
}
$xml->formatOutput = true;
echo "<xmp>". $xml->saveXML() ."</xmp>";
$xml->save("final.xml") or die("Error");
I have created this script to fetch data from csv file and store in xml file . but i am haveing wrong output
my output :
Category ==> SMALL HOME APPLIANCES
Market ==> Breakfast
Segment ==> Hot beverage systems
PIXpro SKU ==> 19392107
it's not printing all the data from csv file but when i deleting
$key = $xml->createElement($key);
$value = $xml->createTextNode($value);
$key->appendChild($value);
$book->appendChild($key);
this code then i am getting all data echo just fine can any help me

Related

Updating array data to a CSV file in php

I want to load csv file data to extract the urls from CSV and check for the title tag for all the urls and update the urls with corresponding title tags in a new csv. But while I try to add data to the csv all the urls are getting listed but only the title of the last url is displayed in the CSV. I have tried different ways to overcome this problem but unable to do so.
Here is my code:
<?php
ini_set('max_execution_time', '300'); //300 seconds = 5 minutes
ini_set('max_execution_time', '0');
include('simple_html_dom.php');
// if (isset($_POST['resurl'])) {
// $url = $_POST['resurl'];
if (($csv_file = fopen("old.csv", "r", 'a')) !== FALSE) {
$arraydata = array();
while (($read_data = fgetcsv($csv_file, 1000, ",")) !== FALSE) {
$column_count = count($read_data);
for ($c = 0; $c < $column_count; $c++) {
array_push($arraydata, $read_data[$c]);
}
}
fclose($csv_file);
}
$title = [];
foreach ($arraydata as $ad) {
$ard = [];
$ard = $ad;
$html = file_get_html($ard);
if ($html) {
$title = $html->find('title', 0)->plaintext;
// echo '<pre>';
// print_r($title);
}
}
$ncsv = fopen("updated.csv", "a");
$head = "Url,Title";
fwrite($ncsv, "\n" . $head);
foreach ($arraydata as $value) {
// $ar[]=$value;
$csvdata = "$value,$title";
fwrite($ncsv, "\n" . $csvdata);
}
fclose($ncsv);
I've changed the code so that you write the CSV file as you read the HTML pages. This saves having another loop and an extra array of titles.
I've also changed it to use fputcsv to write the data out as it sorts ot things like escaping values etc.
// Open file, using w to clear the old file down
$ncsv = fopen('updated.csv', 'w');
$head = 'Url,Title';
fwrite($ncsv, "Url,Title" . PHP_EOL . $head);
foreach ($arraydata as $ad) {
$html = file_get_html($ad);
// Fetch title, or set to blank if html is not loaded
if ($html) {
$title = $html->find('title', 0)->plaintext;
} else {
$title = '';
}
// Write record out
fputcsv($ncsv, [$value, $title]);
}
fclose($ncsv);
I was able to solve it finally.
Here is the updated code:
<?php
ini_set('max_execution_time', '300'); //300 seconds = 5 minutes
ini_set('max_execution_time', '0');
include('simple_html_dom.php');
// if (isset($_POST['resurl'])) {
// $url = $_POST['resurl'];
if (($csv_file = fopen("ntsurl.csv", "r", 'a')) !== FALSE) {
$arraydata = array();
while (($read_data = fgetcsv($csv_file, 1000, ",")) !== FALSE) {
$column_count = count($read_data);
for ($c = 0; $c < $column_count; $c++) {
array_push($arraydata, $read_data[$c]);
}
}
fclose($csv_file);
}
// print_r($arraydata);
$title=[];
$ncsv=fopen("ntsnew.csv","a");
$head="Website Url,title";
fwrite($ncsv,"\n".$head);
foreach($arraydata as $ad)
{
$ard = [];
$ard = $ad;
$html = file_get_html($ard);
if ($html) {
$title = $html->find('title', 0)->plaintext;
echo '<pre>';
print_r($title);
$csvdata="$ard,$title ";
fwrite($ncsv,"\n".$csvdata);
}
}
// fclose($ncsv);

PHP CSV duplicate values

I've got a csv file which contains product datas and prices from two distributors.
There are 67 keys in this file.
Now I want to search all EANs in this file which are twice available and then get the cheapest price.
After that delete the other higher price product line.
The CSV has a key for my merchant.
I made a test csv for easier view:
artno;name;ean;price;merchant
1;ipad;1654213154;499.00;merchant1
809;ipad;1654213154;439.00;merchant2
23;iphone;16777713154;899.00;merchant2
90;iphone;16777713154;799.00;merchant1
After the script runs through, the csv should look like (writing to new file):
artno;name;ean;price;merchant
809;ipad;1654213154;439.00;merchant2
90;iphone;16777713154;799.00;merchant1
I played around with fgetcsv, looping through the csv is not a problem, but how I can search for the ean in key 2?
$filename = './test.csv';
$file = fopen($filename, 'r');
$fileline = 1;
while (($data = fgetcsv($file, 0, ";")) !== FALSE) {
if($fileline == "1"){ $fileline++; continue; }
$search = $data[2];
$lines = file('./test.csv');
$line_number = false;
$count = 0;
while (list($key, $line) = each($lines) and !$line_number) {
$line_number = (strpos($line, $search) !== FALSE) ? $key : $line_number;
$count++;
}
if($count > 2){
echo "<pre>",print_r(str_getcsv($lines[$line_number], ";")),"</pre>";
}
}
I think this is what you are looking for:
<?php
$filename = './test.csv';
$file = fopen($filename, 'r');
$lines = file('./test.csv');
$headerArr = str_getcsv($lines[0], ";");
$finalrawData = [];
$cheapeastPriceByProduct = [];
$dataCounter = 0;
while (($data = fgetcsv($file, 0, ";")) !== FALSE) {
if($dataCounter > 0) {
$raw = str_getcsv($lines[$dataCounter], ";");
$tempArr = [];
foreach( $raw as $key => $val) {
$tempArr[$headerArr[$key]] = $val;
}
$finalrawData[] = $tempArr;
}
$dataCounter++;
}
foreach($finalrawData as $idx => $dataRow ) {
if(!isset($cheapeastPriceByProduct[$dataRow['name']])) {
$cheapeastPriceByProduct[$dataRow['name']] = $dataRow;
}
else {
if(((int)$dataRow['price'])< ((int)$cheapeastPriceByProduct[$dataRow['name']]['price'])) {
$cheapeastPriceByProduct[$dataRow['name']] = $dataRow;
}
}
}
echo "<pre>";
print_r($finalrawData);
print_r($cheapeastPriceByProduct);
I just added $finalData data array to store the parsed data and associated all rows with their header key counterpart then you can compare and filter data based on your criteria.

PHP CSV from S3 as string - want to convert to array

I have some code which downloads a CSV file from an S3 bucket into a PHP variable.
I want to get this CSV content (a string) from this variable and convert it into an array.
I'm having some issues reading from my php://memory resource.
When I print the $csv_fread or $rows I see nothing.
Dumping the $csv_fstat shows the correct length of my file I uploaded and then downloaded and put into the $file_contents string and wrote to the $csv resource.
Any help appreciated.
// use Aws\S3\S3Client;
$result = $this->client->getObject([
'Bucket' => $this->bucket,
'Key' => $id
]);
$file_contents = $result['Body'];
$csv = fopen('php://memory', 'r+');
if ($csv === false) {
throw new Exception('Could not create file wrapper');
}
if (fwrite($csv, $file_contents) === false) {
throw new Exception('Could not write contents to file wrapper');
}
$csv_fstat = fstat($csv);
$csv_fread = fread($csv, $csv_fstat['size']);
if ($csv_fread === false) {
throw new Exception('there was an error reading shit');
}
$header = null;
$rows = [];
while (($row = fgetcsv($csv, 0, ',')) !== false) {
if (!$header) {
$header = [];
foreach ($row as $v) {
$header_raw[] = $v;
$hcounts = array_count_values($header_raw);
$header[] = $hcounts[$v] > 1 ? $v . $hcounts[$v] : $v;
}
} else {
foreach ($row as &$l) {
$l = trim($l);
}
$rows[] = array_combine($header, $row);
}
}
fclose($csv);
I figured out the issue. Needed to do:
rewind($csv);
After fwrite

Add new columns for CSV file

I have tree arrays with different lengths, and I want to display each array in a column of my csv file. That's the php script file I am using but no success; I got the data duplicated.
The attempt I tried was to feed empty cells with an empty string so that I can have 3 columns with the same lengths.
$categories = get_categories( $args );
$categories_level_1 = array();
$categories_level_2 = array();
$categories_level_3 = array();
foreach ($categories as $cat ) {
$cat_level =count( get_ancestors($cat->term_id, 'category') );
if($cat_level == 0){
$categories_level_1[] = $cat;
}else{
if($cat_level == 1){
$categories_level_2[] = $cat;
}elseif($cat_level == 2){
$categories_level_3[] = $cat;
}
}
}
fputcsv($file, array(utf8_decode('Catégories level 1')));
$i=0;
foreach ($categories_level_1 as $category) {
$i++;
$categorie_name = array(rw_mb_convert_encoding($category->name));
fputcsv($file, $categorie_name );
print_flush("\n liine created");
}
while( $i < count($categories_level_2)){
$i++;
fputcsv($file, array(" "));
print_flush("\n liine vide created");
}
fclose($file);
$newCsvData = array();
foreach ($categories_level_2 as $cat) {
if (($handle = fopen($csv_file_path, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$data[] = rw_mb_convert_encoding($cat->name);
$newCsvData[] = $data;
}
fclose($handle);
}
}
$handle = fopen($csv_file_path, 'w');
foreach ($newCsvData as $line) {
fputcsv($handle, $line);
}
fclose($handle);
I should get my columns with the folowwing structure :
But in reality that's the result I got :

Convert csv in php and get unique value

I would like to convert a csv file that has duplicate contents and i would like to sum the quantity and extract the price without sum it.
file.csv :
code,qty,price
001,2,199
001,1,199
002,2,159
002,2,159
Actual php that sum the quantiy and get a result with unique value and total qty.
<?php
$tsvFile = new SplFileObject('file.csv');
$tsvFile->setFlags(SplFileObject::READ_CSV);
$tsvFile->setCsvControl("\t");
$file = fopen('file.csv', 'w');
$header = array('sku', 'qty');
fputcsv($file, $header, ',', '"');
foreach ($tsvFile as $line => $row) {
if ($line > 0) {
if (isset($newData[$row[0]])) {
$newData[$row[0]]+= $row[1];
} else {
$newData[$row[0]] = $row[1];
}
}
}
foreach ($newData as $key => $value) {
fputcsv($file, array($key, $value), ',', '"');
}
fclose($file);
?>
the result for this is:
code,qty
001,3
002,4
and i would like to add price, but without sum it.
The result i need is:
code,qty,price
001,3,199
002,4,159
I haven't tested this yet, but I think this is what you are looking for:
<?php
$tsvFile = new SplFileObject('file.csv');
$tsvFile->setFlags(SplFileObject::READ_CSV);
$tsvFile->setCsvControl("\t");
$file = fopen('file.csv', 'w');
$header = array('sku', 'qty');
fputcsv($file, $header, ',', '"');
foreach ($tsvFile as $line => $row) {
if ($line > 0) {
if(!isset($newData[$row[0]])) {
$newData[$row[0]] = array('qty'=>0, 'price'=>$row[2]);
}
$newData[$row[0]]['qty'] += $row[1];
}
}
foreach ($newData as $key => $arr) {
fputcsv($file, array($key, $arr['qty'], $arr['price']), ',', '"');
}
fclose($file);
?>
To start with, there's a nice function on the PHP page str_getcsv which will help you end up with a more legible array to work with:
function csv_to_array($filename='', $delimiter=',') {
if(!file_exists($filename) || !is_readable($filename))
return FALSE;
$header = NULL;
$data = array();
if (($handle = fopen($filename, 'r')) !== FALSE) {
while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE) {
if(!$header)
$header = $row;
else
$data[] = array_combine($header, $row);
}
fclose($handle);
}
return $data;
}
This is purely for legibility sake but now comes the code which would allow you to work over the array.
$aryInput = csv_to_array('file.csv', ',');
$aryTemp = array();
foreach($aryInput as $aryRow) {
if(isset($aryTemp[$aryRow['code'])) {
$aryTemp[$aryRow['code']['qty'] += $aryRow['qty'];
} else {
$aryTemp[$aryRow['code']] = $aryRow;
}
}
In the above code, it simply:
Loops through the input
Checks whether the key exists in a temporary array
If it does, it just adds the new quantity
If it doesn't, it adds the entire row
Now you can write out your expectant csv file :)

Categories