Compare 2 csv Files in PHP with better Result - php

i found a very good PHP solution here for compareing 2 CSV Files.
The Only Problem is the Result Page..
index.php?f1=re1.csv&f2=re2.csv
<?php
//---- init
$strFileName1=isset($_REQUEST['f1'])?$_REQUEST['f1']:'';
$strFileName2=isset($_REQUEST['f2'])?$_REQUEST['f2']:'';
if ( !$strFileName1 ) { die("I need the first file (f1)"); }
if ( !$strFileName2 ) { die("I need the second file (f2)"); }
try {
$arrFile1 = parseData($strFileName1);
$arrFile2 = parseData($strFileName2);
} catch (Exception $e) {
die($e->getMessage());
}
$rowCount1=count($arrFile1);
$rowCount2=count($arrFile2);
$colCount1=count($arrFile1[0]);
$colCount2=count($arrFile2[0]);
$highestRowCount = $rowCount1>$rowCount2 ? $rowCount1:$rowCount2;
$highestColCount = $colCount1>$colCount2 ? $colCount1:$colCount2;
$row = 0;
$err = 0;
//---- code
echo "<h2>Vergleich $strFileName1 and $strFileName2</h2>";
echo "\n<table border=1>";
echo "\n<tr><th>Err<th>Tabelle<th>Row#<th>Col#<th>Data in $strFileName1<th>Data in $strFileName2";
while($row<$highestRowCount) {
if(!isset($arrFile1[$row])) {
echo "\n<tr><td>Row missing in $strFileName1<th>$row";
$err++;
} elseif(!isset($arrFile1[$row])) {
echo "\n<tr><td>Row missing in $strFileName2<th>$row";
$err++;
} else {
$col=0;
while($col<$highestColCount) {
if ( !isset($arrFile1[$row][$col]) ) {
echo "\n<tr><td>Data missing in $strFileName1<td>$row<td>$col<td><td>".htmlentities($arrFile2[$row][$col]);
$err++;
} elseif ( !isset($arrFile2[$row][$col]) ) {
echo "\n<tr><td>Data missing in $strFileName1<td>$row<td>$col<td>".htmlentities($arrFile1[$row][$col]) ."<td>";
$err++;
} elseif ( $arrFile1[$row][$col] != $arrFile2[$row][$col] ) {
echo "\n<tr><td>Data mismatch";
echo "<td>Tabelle <td>$row <td>$col";
echo "<td>".htmlentities($arrFile1[$row][$col]);
echo "<td>".htmlentities($arrFile2[$row][$col]);
$err++;
}
$col++;
}
}
$row++;
}
echo "</table>";
if ( !$err ) {
echo "<br/>\n<br/>\nThe two csv data files seem identical<br/>\n";
} else {
echo "<br/>\n<br/>\nThere are $err differences";
}
//---- functions
function parseData($strFilename) {
$arrParsed = array();
$handle = fopen($strFilename , "r");
if ($handle) {
while (!feof($handle)) {
$data = fgetcsv($handle , 0 , ',' , '"' );
if ( empty($data)) continue; //empty row
$arrParsed[]=$data;
}
fclose($handle);
} else {
throw new Exception("File read error at $strFilename");
}
return $arrParsed;
}
?>
The Result displays the Row# and Col# of the file..
but what i need is the Name of the Col..
This is how my CSV looks like:
ISO_COUNTRY_CODE,CNT_POSTAL_CODE,ORDER1_ADMIN_TYP_1112,ORDER2_ADMIN_TYP_1113,ORDER8_ADMIN_TYP_1119,BUILTUP_ID
AND,7,0,0,7,40
ARG,1970,25,0,514,4076
AUS,2612,9,0,10978,4597
AUT,2213,9,95,2354,10304
BEL,1148,3,11,589,3781
BGR,4507,28,0,264,5375
I want to see in which "ISO_COUNTRY_CODE" is the CNT_POSTAL_CODE wrong..
$rowname = $row; // here i want to see the RAW of the Table
"like AND or ARG etc"
$colname = $col; // here i want to see the COL of the Table
"like CNT_POSTAL_CODE
or ORDER1_ADMIN_TYP_1112 etc "

Related

PHP Simplexml iterator

How to elaborate an array reflecting the structure of the following xml ?
Thanks in advance.
XML source :
<document>
<section type="group" width="100">
<section type="list" width"50"/>
<style>classe1 {color:red}</style>
<section type="text" height="25">azerty</section>
</section>
</document>
Please note the three tags ('section', 'style' then 'section') embedded in the first level 'section'
Example of desired generated array should reflecting this embedding, attributes and tags order :
Array
{
[0]=>Array
{
[key]=>section
[attributes]=>Array
{
[type]=>group
[width]=>100
}
[0]=>Array
{
[key]=>section
[attributes]=>Array
{
[type]=>list
[width]=>50
}
}
[1]=>Array
{
[key]=>style
[content]=>classe1 {color:red}
}
[2]=>Array
{
[key]=>section
[attributes]=>Array
{
[type]=>text
[width]=>25
}
[content]=>azerty
}
}
}
I tried without success whith this code :
<?php
function xml2array($fName)
{
$sxi = new SimpleXmlIterator($fName, null, true);
return sxiToArray($sxi);
}
function sxiToArray($sxi)
{
$a = array();
for( $sxi->rewind(); $sxi->valid(); $sxi->next() )
{
if(!array_key_exists($sxi->key(), $a))
$a[$sxi->key()] = array();
if($sxi->hasChildren())
$a[$sxi->key()][] = sxiToArray($sxi->current());
else
{
$a[$sxi->key() ]['attributs'] = $sxi->attributes();
$a[$sxi->key()][] = strval($sxi->current());
}
}
return $a;
}
try
{
$catArray = xml2array("temp.xml");
echo '<pre>'.print_r($catArray,true);
}
catch(Exception $e)
{
echo 'ERREUR : '.$e->getMessage();
}
?>
I've updated the code to achieve what I think your after. There are a few bits where I've managed the arrays differently. Especially with attributes - I've added them one at a time to allow me to create the key/value setup.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
function xml2array($fName)
{
$sxi = new SimpleXmlIterator($fName, null, true);
$sxi->rewind();
return sxiToArray($sxi)[0];
}
function sxiToArray($sxi)
{
$a = array();
for( $sxi->rewind(); $sxi->valid(); $sxi->next() )
{
$newData = [];
$newData['key'] = $sxi->key();
foreach ( $sxi->current()->attributes() as $key=>$attribute) {
$newData['attributes'][(string)$key] = (string)$attribute;
}
if($sxi->hasChildren()) {
$newData = array_merge( $newData, sxiToArray($sxi->current()));
}
else
{
if ( strlen(strval($sxi->current())) > 0 ) {
$newData['content'] = strval($sxi->current());
}
}
$a[] = $newData;
}
return $a;
}
try
{
$catArray = xml2array("t1.xml");
echo '<pre>'.print_r($catArray,true);
}
catch(Exception $e)
{
echo 'ERREUR : '.$e->getMessage();
}
{
echo 'ERREUR : '.$e->getMessage();
}
I also had to correct the XML as
<section type="list" width"50"/>
should be
<section type="list" width="50"/>
(missing =)

count the rows based on array object

I want to count the rows based on like and unlike value in an array.I want to count the rows based on like and unlike value.I need to display like:3 and unlike:1.Now it display like:0,unlike:0 '$content' value is either {"userid":"1","like":"1"} or {"userid":"1","unlike":"1"}
$like_count = 0;
$unlike_count = 0;
while($like_fet = mysql_fetch_assoc($query))
{
$content = $like_fet['CONTENT_VALUE'];
$datas = json_decode($content);
foreach($datas as $item)
{
$like = $item['like'];
$unlike = $item['unlike'];
if($like != '' && $unlike == '')
{
echo "like";
$like_count++;
}
if($unlike != '' && $like == '')
{
echo "unlike";
$unlike_count++;
}
}
}
$like_count=0;
$unlike_count=0;
while($like_fet=mysql_fetch_assoc($query)) {
$json = json_decode($like_fet['CONTENT_VALUE'], true);
if ( isset($json['like']) ) {
$like_count += $json['like'];
}
if ( isset($json['unlike']) ) {
$unlike_count += $json['unlike'];
}
}
depending on how CONTENT_VALUE actually works this can probably simplified to
$like_count=0;
$unlike_count=0;
while($like_fet=mysql_fetch_assoc($query)) {
$json = json_decode($like_fet['CONTENT_VALUE'], true);
if ( isset($json['like']) ) {
$like_count++;
}
else if ( isset($json['unlike']) ) {
$unlike_count++;
}
else {
trigger_error('CONTENT_VALUE without like/unlike element', E_USER_NOTICE);
}
}

Value of variable changes in while-loop

Me and all my live contact are stunned by phenomenom where a variable value changes in other side ow while. Before 2nd loop value is correct, but inside 2nd loop value is incorrect.
Here's the actual code.
try {
$yhteys = new PDO('mysql:host=localhost;dbname=XXXX', 'YYYY', 'ZZZZ');
} catch (PDOException $e) {
die("VIRHE: " . $e->getMessage());
}
$yhteys->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$yhteys->exec("SET NAMES utf8");
$kysely = $yhteys->prepare('SELECT viite FROM hakija WHERE vaihe = 1 ');
$kysely->execute();
$file = fopen("tilit.csv","r");
while(! feof($file)) {
$tilirivi=fgetcsv($file,100,";");
if ($tilirivi[4] < 0) continue;
$viiteviesti = substr($tilirivi[3], 1);
//print "Viiteviesti1: $viiteviesti\n"; produces correct print
while ($rivi = $kysely->fetch()) {
//print "Viiteviesti2: $viiteviesti\n"; produces incorrect print
$kantaviite=$rivi["viite"];
if ($viiteviesti == $kantaviite ) {
$asetus = $yhteys->prepare("UPDATE hakija SET vaihe=2 WHERE viite='$viiteviesti' ");
$asetus->execute();
}
}
}
How is this possible and how should I correct my code?
'column' is a reserved variable name according to this article:
http://hockinson.com/programmer-web-designer-denver-co-usa.php?s=43
which might cause unexpected results.
It came up that for some reason $kysely-fecth() didn't return any content. I got the code working and here's solution:
try {
$yhteys = new PDO('mysql:host=localhost;dbname=XXXX', 'YYYY', 'ZZZZ');
} catch (PDOException $e) {
die("VIRHE: " . $e->getMessage());
}
$yhteys->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$yhteys->exec("SET NAMES utf8");
$kysely = $yhteys->prepare('SELECT viite FROM hakija WHERE vaihe = 1 ');
$kysely->execute();
$kysely->setFetchMode(PDO::FETCH_NUM);
$result = $kysely->fetchAll();
$file = fopen("tilit.csv","r");
while(! feof($file)) {
$tilirivi=fgetcsv($file,100,";");
if ($tilirivi[4] < 10) continue;
$viiteviesti = substr($tilirivi[3], 1);
foreach ($result as $rivi) {
foreach ($rivi as $kantaviite) {
if ($viiteviesti == $kantaviite ) {
$asetus = $yhteys->prepare("UPDATE hakija SET vaihe=2 WHERE viite='$viiteviesti' ");
$asetus->execute();
}
}
}
}

PHP is exiting earily on csv export

I'm trying to export a list of contacts with a specified set of fields from in Codeigniter. PHP is exiting early and I can't figure out why. It exports 4,092 contacts then exits but the count of the array being exported is 140,699. PHP gives me no errors, and on my test server the export function works fine. Here's the code:
function admin_export()
{
set_time_limit(0);
if(!$this->ion_auth->in_group(array('admin')) && !$this->input->is_cli_request())
die();
$contacts = $this->contacts_model->get_contacts();
$export_fields = unserialize($this->contacts_model->get_contact_export_fields());
if(!file_exists($this->config->item('tmp_path')))
mkdir($this->config->item('tmp_path'));
if($export_fields == false)
{
echo json_encode(false);
}
else
{
$fh = fopen($this->config->item('tmp_path').'export.csv', 'w');
fputcsv($fh, $export_fields, ',');
foreach($contacts as $i => $contact)
{
$id = $contact['id'];
foreach($contact as $k => $v)
{
if(!in_array($k, $export_fields))
{
unset($contacts[$i][$k]);
}
}
if(in_array('role', $export_fields))
{
$contacts[$i]['role'] = '';
$roles = $this->contacts_model->get_contact_roles($id);
foreach($roles as $role)
{
$contacts[$i]['role'] .= $role['role'].';';
}
$contacts[$i]['role'] = rtrim($contacts[$i]['role'], ';');
}
if(in_array('role_id', $export_fields))
{
$contacts[$i]['role_id'] = '';
$role_ids = $this->contacts_model->get_contact_roles($id);
foreach($role_ids as $role_id)
{
$contacts[$i]['role_id'] .= $role_id['id'].';';
}
$contacts[$i]['role_id'] = rtrim($contacts[$i]['role_id'], ';');
}
fputcsv($fh, $contacts[$i], ',');
}
fclose($fh);
echo json_encode(true);
}
}
What about memory? It's possible that it is maxing out the allocated memory and stopping.

preventing duplicate files in php

Trying to prevent a file from being duplicated in a users directory. This is what I have come up with,
$data = $connection->getMedia($fileid);
/**
* The test begins
*/
$dir = 'media/download/'.$username;
$files1 = scandir($dir);
foreach ($files1 as $i => $file) {
if (md5($file) == md5($data)) {
//statement
echo "Duplicate entry detected.";
}
else {
file_put_contents($finalPath, $data);
}
This, however, gives me an endless loop and I cant see what it is doing. So, can anyone give me a better idea.?
EDIT: the full code:
foreach ($accounts as $username => $password) {
$connection= new Connection($username,$password);
$fileList= $connection->getFiles();
echo '<br><p>Last available files for '.$username.': <br>';
if (!file_exists('media/download/'.$username)) {
mkdir('media/download/'.$username, 0777, true);
}
for ($i=0;$i<7;$i++)
{
$fileID= $fileList[$i]->id;
$data = $connection->getMedia($fileID);
if (!strlen($data) < 1 ) {
$recipient = $fileList[$i]->recipient;
$finalPath = 'media/download/'.$username.'/to'.$recipient.'_id'.$fildID.rand(0,200).'.jpg';
file_put_contents($finalPath, $data);
echo " <img src='".$finalPath."' height='100' width='100'> ";
}
}
}

Categories