Here is my code which works well:
<?php
if(isset($_POST['btn'])){
$search=$_POST['search'];
require_once('Apache/Solr/Service.php');
$solr=new Apache_Solr_Service( 'localhost', '8983', '/solr' );
$offset = 0;
$limit = 10;
$queries = array(
'title:*'.$search.'*'
);
foreach ($queries as $query) {
$response = $solr->search($query, $offset, $limit);
if ($response->getHttpStatus() == 200) {
// print_r( $response->getRawResponse() );
if ($response->response->numFound > 0) {
foreach ($response->response->docs as $doc) {
echo '<pre>';
echo 'title ='.$doc->title;
echo '<br>';
echo 'image='.$doc->image;
echo '</pre>';
}
echo '<br />';
}
} else {
echo $response->getHttpStatusMessage();
}
}
}
?>
It searches for what $_POST['search'] is. But I want to use something named Solr Client. Because it has a method named $solrQuery->set('spellcheck','true'); that gives you the "did you mean x ?" feature.
I've followed this from the doc with no success. It throws SolrClient class not found.
Any clue how can I use SolrClient and what's its different with Apache_Solr_Service ?
Related
I am using Moodle version 3.8.4+ and PHP version 7.2.33 . Today I noticed a strange issue when I was trying to send a message to students, the message was:
Coding error detected, it must be fixed by a programmer: Url parameters values can not be arrays! More information about this error
I purge all caches as the suggestion was on "more information" section but it did not work.
I run the same Moodle version and PHP version on non production environment with the debugging mode and then I got this error message:
Coding error detected, it must be fixed by a programmer: Url parameters values can not be arrays!
More information about this error
Debug info:
Error code: codingerror
Stack trace:
line 405 of /lib/weblib.php: coding_exception thrown
line 460 of /lib/weblib.php: call to moodle_url->params()
line 49 of /mod/reservation/messageselect.php: call to moodle_url->param()
Output buffer: Invalid array parameter detected in required_param(): messagebody
line 655 of /lib/moodlelib.php: call to debugging()
line 30 of /mod/reservation/messageselect.php: call to optional_param()
The messageselect.php file is this but I am not able to see any issues here:
require_once('../../config.php');
require_once($CFG->dirroot.'/message/lib.php');
$id = required_param('id', PARAM_INT);
$messagebody = optional_param('messagebody', '', PARAM_CLEANHTML);
$send = optional_param('send', '', PARAM_BOOL);
$preview = optional_param('preview', '', PARAM_BOOL);
$edit = optional_param('edit', '', PARAM_BOOL);
$returnto = optional_param('returnto', new moodle_url('/mod/reservation/view.php', array('id' => $id)), PARAM_LOCALURL);
$format = optional_param('format', FORMAT_MOODLE, PARAM_INT);
$deluser = optional_param('deluser', 0, PARAM_INT);
if (isset($id)) {
if (! $cm = get_coursemodule_from_id('reservation', $id)) {
error('Course Module ID was incorrect');
}
if (! $course = $DB->get_record('course', array('id' => $cm->course))) {
error('Course is misconfigured');
}
}
$url = new moodle_url('/mod/reservation/messageselect.php', array('id' => $id));
if ($messagebody !== '') {
$url->param('messagebody', $messagebody);
}
if ($send !== '') {
$url->param('send', $send);
}
if ($preview !== '') {
$url->param('preview', $preview);
}
if ($edit !== '') {
$url->param('edit', $edit);
}
if ($returnto !== '') {
$url->param('returnto', $returnto);
}
if ($format !== FORMAT_MOODLE) {
$url->param('format', $format);
}
if ($deluser !== 0) {
$url->param('deluser', $deluser);
}
$modulecontext = context_module::instance($cm->id);
$PAGE->set_url($url);
$PAGE->set_context($modulecontext);
require_login($course->id, false, $cm);
$coursecontext = context_course::instance($course->id);
$systemcontext = context_system::instance();
require_capability('moodle/course:bulkmessaging', $coursecontext);
if (empty($SESSION->reservation_messageto)) {
$SESSION->reservation_messageto = array();
}
if (!array_key_exists($id, $SESSION->reservation_messageto)) {
$SESSION->reservation_messageto[$id] = array();
}
if ($deluser) {
$idinmessageto = array_key_exists($id, $SESSION->reservation_messageto);
if ($idinmessageto && array_key_exists($deluser, $SESSION->reservation_messageto[$id])) {
unset($SESSION->reservation_messageto[$id][$deluser]);
}
}
if (empty($SESSION->reservation_messageselect[$id]) || $messagebody) {
$SESSION->reservation_messageselect[$id] = array('messagebody' => $messagebody);
}
$messagebody = $SESSION->reservation_messageselect[$id]['messagebody'];
$count = 0;
if ($data = data_submitted()) {
require_sesskey();
foreach ($data as $k => $v) {
if (preg_match('/^(user|teacher)(\d+)$/', $k, $m)) {
if (!array_key_exists($m[2], $SESSION->reservation_messageto[$id])) {
$returnfields = 'id,firstname,lastname,idnumber,email,mailformat,lastaccess, lang, maildisplay';
if ($user = $DB->get_record_select('user', "id = ?", array($m[2]), $returnfields)) {
$SESSION->reservation_messageto[$id][$m[2]] = $user;
$count++;
}
}
}
}
}
$strtitle = get_string('message', 'reservation');
$PAGE->navbar->add($strtitle);
$PAGE->set_title($strtitle);
$PAGE->set_heading($strtitle);
echo $OUTPUT->header();
// If messaging is disabled on site, we can still allow users with capabilities to send emails instead.
if (empty($CFG->messaging)) {
echo $OUTPUT->notification(get_string('messagingdisabled', 'message'));
}
if ($count) {
if ($count == 1) {
$heading = get_string('addedrecip', 'moodle', $count);
} else {
$heading = get_string('addedrecips', 'moodle', $count);
}
echo $OUTPUT->heading($heading);
}
if (!empty($messagebody) && !$edit && !$deluser && ($preview || $send)) {
require_sesskey();
if (count($SESSION->reservation_messageto[$id])) {
if (!empty($preview)) {
echo '<form method="post" action="messageselect.php" style="margin: 0 20px;">
<input type="hidden" name="returnto" value="'.s($returnto).'" />
<input type="hidden" name="id" value="'.$id.'" />
<input type="hidden" name="format" value="'.$format.'" />
<input type="hidden" name="sesskey" value="' . sesskey() . '" />
';
echo "<h3>".get_string('previewhtml')."</h3>";
echo "<div class=\"messagepreview\">\n".format_text($messagebody, $format)."\n</div>\n";
echo '<p align="center"><input type="submit" name="send" value="'.get_string('sendmessage', 'message').'" />'."\n";
echo '<input type="submit" name="edit" value="'.get_string('update').'" /></p>';
echo "\n</form>";
} else if (!empty($send)) {
$fails = array();
foreach ($SESSION->reservation_messageto[$id] as $user) {
if (!message_post_message($USER, $user, $messagebody, $format)) {
$user->fullname = fullname($user);
$fails[] = get_string('messagedselecteduserfailed', 'moodle', $user);
};
}
if (empty($fails)) {
echo $OUTPUT->heading(get_string('messagedselectedusers'));
unset($SESSION->reservation_messageto[$id]);
unset($SESSION->reservation_messageselect[$id]);
} else {
echo $OUTPUT->heading(get_string('messagedselectedcountusersfailed', 'moodle', count($fails)));
echo '<ul>';
foreach ($fails as $f) {
echo '<li>', $f, '</li>';
}
echo '</ul>';
}
echo '<p align="center">'.get_string('backtoparticipants').'</p>';
}
echo $OUTPUT->footer();
exit;
} else {
echo $OUTPUT->notification(get_string('nousersyet'));
}
}
echo '<p align="center">'.get_string("keepsearching").''.
((count($SESSION->reservation_messageto[$id])) ? ', '.get_string('usemessageform') : '').'</p>';
if ((!empty($send) || !empty($preview) || !empty($edit)) && (empty($messagebody))) {
echo $OUTPUT->notification(get_string('allfieldsrequired'));
}
if (count($SESSION->reservation_messageto[$id])) {
require_sesskey();
require("message.html");
}
$PAGE->requires->yui_module('moodle-core-formchangechecker',
'M.core_formchangechecker.init',
array(array(
'formid' => 'theform'
))
);
$PAGE->requires->string_for_js('changesmadereallygoaway', 'moodle');
echo $OUTPUT->footer();
```php
It looks like the massagebody param in the request that initiates this process is using array syntax, like ?messagebody[]=foo instead of ?messagebody=foo, so the error is in whatever page the request originated from. You can either try to figure out why that is and change it, or make a change to this messageselect.php file to flatten the parameter. To do that you would change this:
<?php
if ($messagebody !== '') {
$url->param('messagebody', $messagebody);
}
to this:
<?php
if ($messagebody !== '') {
if(is_array($messagebody))
{
$messagebody = array_shift($messagebody);
}
$url->param('messagebody', $messagebody);
}
However be aware that if the page is sending this parameter as an array, it is quite likely that others will be sent that way as well. Usually you would send parameters using array syntax so that multiple records can be processed in one request, so that messagebody[1] would correlate to format[1], messagebody[2] would correlate to format[2], and so on. The code in messageselect.php is clearly not expecting this. I would be interested to find out what the story is for the page that sends requests here.
I am trying to get the faceting results and I don't know how. there are no documentation for solr-php-client. In this example, print_r( $response->getRawResponse() ) does not include faceting. I am not sure weather faceting is not successfully requested or it is a matter of accessing the faceting data in the responce. Please also help me if there is any documentation available online for solr-php-client.
An other question is how to declare "user/password" if solr is protected when initiating the instance of solr-php-client
require_once( 'solr-php-client/Apache/Solr/Service.php' );
$solr = new Apache_Solr_Service( 'localhost', '8983', '/solr/products' );
if ( ! $solr->ping() ) {
echo 'Solr service not responding.';
exit;
}
$offset = 0;
$limit = 10;
$queries = array(
'name:iphone'
);
$additionalParameters = array(
'facet' => 'true',
'facet.field' => array(
'category'
)
);
foreach ( $queries as $query ) {
$response = $solr->search( $query, $offset, $limit );
if ( $response->getHttpStatus() == 200 ) {
print_r( $response->getRawResponse() );
if ( $response->response->numFound > 0 ) {
echo "$query <br />";
foreach ( $response->response->docs as $doc ) {
echo "$doc->id $doc->name <br />";
}
echo '<br />';
}else{
echo "zero results";
}
}
else {
echo $response->getHttpStatusMessage();
}
}
I missed to add $additionalParameters to the search arguements;
$response = $solr->search( $query, $offset, $limit,$additionalParameters );
I recently inherited a RSS/XML parser, and while it seems to work really good, I'm finding some things are missing.
For instance, pulling in a RSS feed from a blog. It's missing all the categories in the items. It shows as each item having only one category when in reality it should show as having a multitude of categories.
Link to Demo: http://dev.o7t.in/rss/
Link to Actual Feed: http://o7thblog.com/feed/
You can see how the first item in the feed itself has 8 total categories in the first item. (may need to view source)
However, in the Demo you can see that it only shows 1 category
Here is my entire code for the class:
<?php
class o7thRssFeedPuller{
public $FeedUrl = ''; // URL of the feed to pull in
public $ReturnJson = false; // Return the array as a JSON encoded string instead?
public $MaxItems = 0; // 0 = unlimited (except by feed), only applicable to GetItems
// Internal holders
private $document;
private $channel;
private $items;
// Get the full RSS feed
public function GetRSS($includeAttributes = false) {
// Pull in our feed
$this->loadParser(file_get_contents($this->FeedUrl, false, $this->randomContext()));
if($includeAttributes) {
// only if we are including attributes
return ($this->ReturnJson) ? json_encode($this->document) : $this->document;
}
// Return either an array or a json encoded string
return ($this->ReturnJson) ? json_encode($this->valueReturner()) : $this->valueReturner();
}
// Get the channel data
public function GetChannel($includeAttributes = false) {
// Pull in our feed
$this->loadParser(file_get_contents($this->FeedUrl, false, $this->randomContext()));
if($includeAttributes) {
// only if we are including attributes
return ($this->ReturnJson) ? json_encode($this->channel) : $this->channel;
}
// Return either an array or a json encoded string
return ($this->ReturnJson) ? json_encode($this->valueReturner($this->channel)) : $this->valueReturner($this->channel);
}
// Get the items
public function GetItems($includeAttributes=false) {
// Pull in our feed
$this->loadParser(file_get_contents($this->FeedUrl, false, $this->randomContext()));
if($includeAttributes) {
// only if we are including attributes
$arr = ($this->MaxItems == 0) ? $this->items : array_slice($this->items, 0, $this->MaxItems);
return ($this->ReturnJson) ? json_encode($arr) : $arr;
}
// Return either an array or a json encoded string
$arr = ($this->MaxItems == 0) ? $this->valueReturner($this->items) : array_slice($this->valueReturner($this->items), 0, $this->MaxItems);
return ($this->ReturnJson) ? json_encode($arr) : $arr;
}
// -------------------------------------------------------------------------------------------------
// Internal Methods
private function loadParser($rss=false) {
if($rss) {
$this->document = array();
$this->channel = array();
$this->items = array();
$DOMDocument = new DOMDocument;
$DOMDocument->strictErrorChecking = false;
$DOMDocument->loadXML($rss);
$this->document = $this->extractDOM($DOMDocument->childNodes);
}
}
private function valueReturner($valueBlock=false) {
if(!$valueBlock) {
$valueBlock = $this->document;
}
foreach($valueBlock as $valueName => $values) {
if(isset($values['value'])) {
$values = $values['value'];
}
if(is_array($values)) {
$valueBlock[$valueName] = $this->valueReturner($values);
} else {
$valueBlock[$valueName] = $values;
}
}
return $valueBlock;
}
private function extractDOM($nodeList,$parentNodeName=false) {
$itemCounter = 0;
foreach($nodeList as $values) {
if(substr($values->nodeName,0,1) != '#') {
if($values->nodeName == 'item') {
$nodeName = $values->nodeName.':'.$itemCounter;
$itemCounter++;
} else {
$nodeName = $values->nodeName;
}
$tempNode[$nodeName] = array();
if($values->attributes) {
for($i=0;$values->attributes->item($i);$i++) {
$tempNode[$nodeName]['properties'][$values->attributes->item($i)->nodeName] = $values->attributes->item($i)->nodeValue;
}
}
if(!$values->firstChild) {
$tempNode[$nodeName]['value'] = $values->textContent;
} else {
$tempNode[$nodeName]['value'] = $this->extractDOM($values->childNodes, $values->nodeName);
}
if(in_array($parentNodeName, array('channel','rdf:RDF'))) {
if($values->nodeName == 'item') {
$this->items[] = $tempNode[$nodeName]['value'];
} elseif(!in_array($values->nodeName, array('rss','channel'))) {
$this->channel[$values->nodeName] = $tempNode[$nodeName];
}
}
} elseif(substr($values->nodeName,1) == 'text') {
$tempValue = trim(preg_replace('/\s\s+/',' ',str_replace("\n",' ', $values->textContent)));
if($tempValue) {
$tempNode = $tempValue;
}
} elseif(substr($values->nodeName,1) == 'cdata-section'){
$tempNode = $values->textContent;
}
}
return (!isset($tempNode)) ? null : $tempNode;
}
// Load in a random header to pass
private function randomContext() {
$headerstrings = array();
$headerstrings['User-Agent'] = 'Mozilla/5.0 (Windows; U; Windows NT 5.'.rand(0,2).'; en-US; rv:1.'.rand(2,9).'.'.rand(0,4).'.'.rand(1,9).') Gecko/2007'.rand(10,12).rand(10,30).' Firefox/2.0.'.rand(0,1).'.'.rand(1,9);
$headerstrings['Accept-Charset'] = rand(0,1) ? 'en-gb,en;q=0.'.rand(3,8) : 'en-us,en;q=0.'.rand(3,8);
$headerstrings['Accept-Language'] = 'en-us,en;q=0.'.rand(4,6);
$setHeaders = 'Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5'."\r\n".
'Accept-Charset: '.$headerstrings['Accept-Charset']."\r\n".
'Accept-Language: '.$headerstrings['Accept-Language']."\r\n".
'User-Agent: '.$headerstrings['User-Agent']."\r\n";
$contextOptions = array(
'http'=>array(
'method'=>"GET",
'header'=>$setHeaders
)
);
return stream_context_create($contextOptions);
}
}
?>
And for the demo page:
<?php
require_once($_SERVER['DOCUMENT_ROOT'] . '/rss/o7th.rss.feed.puller.php');
$fp = new o7thRssFeedPuller();
$fp->FeedUrl = 'http://o7thblog.com/feed';
$fp->MaxItems = 2;
echo '<table width="100%" cellpadding="0" cellspacing="0">';
echo ' <tr>';
echo ' <td>';
echo ' <textarea cols="120" rows="30">';
print_r($fp->GetItems());
echo ' </textarea>';
echo ' </td>';
echo ' </tr>';
echo '</table>';
?>
So, I assume that the issue lies somewhere in either the valueReturner method or the extractDOM method, but I am just not sure where, nor what I can do to get all the categories in the returned array.
Can you help?
I would suggest using SimpleXML to parse the feed.
Here is how you can do it:
$feed_url = 'http://o7thblog.com/feed/';
$feed = simplexml_load_file($feed_url, null, LIBXML_NOCDATA);
$channel = $feed->channel;
echo "<h1>{$channel->title}</h1>\n";
echo "{$channel->description}\n";
echo "<dl>\n";
foreach ($channel->item as $item) {
echo "<dt>{$item->title}</dt>\n"
. "<dd style=\"margin-bottom: 30px;\"><div style=\"font-size: small;\">{$item->pubDate}</div>\n"
. "<div>{$item->description}</div>\n"
. "Categories: <strong>".implode('</strong>, <strong>', (array) $item->category) . "</strong>\n</dd>";
}
echo "</dl>\n";
Above shows you all categories.
You have written a custom parser for what you can do simply with one line of code!
$feed = (array) simplexml_load_file('http://o7thblog.com/feed/', null, LIBXML_NOCDATA);
I'm trying to use heavy resource content loop operation with ZeroMQ (PHP-ZMQ) via tcp protocol.
I've got below code so far:
class SJB_Miscellaneous_SendNotifications extends SJB_Function
{
public function execute()
{
try{
set_time_limit(0);
$i18n = SJB_I18N::getInstance();
$lang = $i18n->getLanguageData($i18n->getCurrentLanguage());
$current_date = strftime($lang['date_format'], time());
// Send Search Notifications
$saved_searches = SJB_SavedSearches::getAutoNotifySavedSearches();
// echo "<pre>"; print_r($saved_searches); echo "</pre>"; exit;
$listing = new SJB_Listing();
$notified_saved_searches_sid = array();
$notificationsLimit = (int) SJB_Settings::getSettingByName('num_of_listings_sent_in_email_alerts');
/* ZeroMQ implementation */
$queue = new ZMQSocket(new ZMQContext(), ZMQ::SOCKET_REQ, "MySock1");
$queue->connect("tcp://127.0.0.1:5555");
/* Assign socket 1 to the queue, send and receive */
$time = time();
$queue->send(json_encode($saved_searches));
// echo $queue->recv();
// exit;
$count = 1;
// array_shift($saved_searches);
$server = new ZMQSocket(new ZMQContext(), ZMQ::SOCKET_REP);
$server->bind("tcp://127.0.0.1:5555");
$msg = $server->recv();
$saved_searches = json_decode($msg, true);
// echo "<pre>"; var_dump($saved_searches); echo "</pre>";
// exit;
foreach ($saved_searches as $saved_search) {
$searcher = new SJB_ListingSearcher();
$listing->addActivationDateProperty();
$search_data = unserialize($saved_search['data']);
$search_data['active']['equal'] = 1;
$datearr = explode('-', $saved_search['last_send']);
$saved_search['last_send'] = strftime($lang['date_format'], mktime(0, 0, 0, $datearr[1], $datearr[2], $datearr[0]));
$search_data['activation_date']['not_less'] = $saved_search['last_send'];
$search_data['activation_date']['not_more'] = $current_date;
$listing_type_sid = 0;
if ($search_data['listing_type']['equal']) {
$listing_type_id = $search_data['listing_type']['equal'];
$listing_type_sid = SJB_ListingTypeManager::getListingTypeSIDByID($listing_type_id);
if (SJB_ListingTypeManager::getWaitApproveSettingByListingType($listing_type_sid))
$search_data['status']['equal'] = 'approved';
}
// echo "<pre>"; echo $saved_search['user_sid']; print_r($listing_type_id); echo "</pre>"; exit;
$id_alias_info = $listing->addIDProperty();
$username_alias_info = $listing->addUsernameProperty();
$listing_type_id_info = $listing->addListingTypeIDProperty();
$aliases = new SJB_PropertyAliases();
$aliases->addAlias($id_alias_info);
$aliases->addAlias($username_alias_info);
$aliases->addAlias($listing_type_id_info);
$search_data['access_type'] = array(
'accessible' => $saved_search['user_sid'],
);
$criteria = SJB_SearchFormBuilder::extractCriteriaFromRequestData($search_data, $listing);
$searcher->found_object_sids = array();
$searcher->setLimit($notificationsLimit);
$sorting_fields = array('CityRegion' => 'ASC');
$found_listings_ids = $searcher->getObjectsSIDsByCriteria($criteria, $aliases, $sorting_fields);
// echo "<pre>"; var_dump($found_listings_ids); echo "</pre>";
if (count($found_listings_ids)) {
$saved_search['activation_date'] = $saved_search['last_send'];
if (SJB_Notifications::sendUserNewListingsFoundLetter($found_listings_ids, $saved_search['user_sid'], $saved_search, $listing_type_sid)) {
SJB_Statistics::addStatistics('sentAlert', $listing_type_sid, $saved_search['sid']);
SJB_DB::query('UPDATE `saved_searches` SET `last_send` = CURDATE() WHERE `sid` = ?n', $saved_search['sid']);
}
$notified_saved_searches_sid[] = $saved_search['sid'];
}
echo nl2br($count."\n");
$count++;
}
// To be entered from task_scheduler.php
$expired_contracts_id = null; $expired_listings_id = null;
$template_processor = SJB_System::getTemplateProcessor();
$template_processor->assign('expired_listings_id', null);
$template_processor->assign('deactivated_listings_id', null);
$template_processor->assign('expired_contracts_id', null);
$template_processor->assign('notified_saved_searches_id', $notified_saved_searches_sid);
$scheduler_log = $template_processor->fetch('task_scheduler_log.tpl');
if ($log_file = #fopen('task_scheduler.log', 'a+')) {
fwrite($log_file, $scheduler_log);
fclose($log_file);
}
SJB_DB::query('INSERT INTO `task_scheduler_log`
(`last_executed_date`, `notifieds_sent`, `expired_listings`, `expired_contracts`, `log_text`)
VALUES ( NOW(), ?n, ?n, ?n, ?s)',
count($notified_saved_searches_sid), count($expired_listings_id), count($expired_contracts_id), $scheduler_log);
} catch(Exception $e){
echo $e->getMessage();
}
}
} // END class SJB_Miscellaneous_SendNotifications extends SJB_Function
Is there a good way to utilise ZeroMQ for this type of operation where I want to free loop operations especially when it reaches $saved_searches foreach loop?
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 "