The following code parses an XML file and displays the results. The function resultSort is meant to sort the results by price from highest to lowest. Unfortunately, it's not sorting correctly in all cases. I think this may be due to the prices being in euros. Right now, this is how it outputs the results:
1 208,00
2 148,00
412,00
638,00
942,00
This is how it should look:
2 148,00
1 208,00
942,00
638,00
412,00
Here's the code:
class StoreList {
var $parser;
var $record;
var $current_field;
var $field_type;
var $ends_record;
var $records;
function resultSort($item1, $item2) {
if($item1['price'] == $item2['price']) return 0;
return $item1['price'] < $item2['price'] ? -1 : 1;
}
function StoreList ($filename) {
$this ->parser = xml_parser_create();
xml_set_object($this->parser, &$this);
xml_set_element_handler($this->parser, 'start_element', 'end_element');
xml_set_character_data_handler($this->parser, 'cdata');
// 1 = single field, 2 = array field
$this->field_type=array('Title' => 1,
'storeName' => 1,
'price' => 1,
'storeURL' => 2,
'description' => 1,
'brand' => 1);
$this->ends_record = array('result' => true);
$x = join("", file($filename));
xml_parse($this->parser, $x);
xml_parser_free($this->parser);
}
function start_element($p, $element, &$attributes) {
$element = strtolower($element);
if ($this->field_type[$element] != 0) {
$this->current_field = $element;
} else {
$this->current_field = '';
}
}
function end_element ($p, $element) {
$element = strtolower($element);
if ($this->ends_record[$element]) {
$this->records[] = $this->record;
$this->record = array();
}
$this->current_field = '';
}
function cdata ($p, $text) {
if ($this->field_type[$this->current_field] === 2) {
$this->record[$this->current_field][] = $text;
} elseif ($this->field_type[$this->current_field] === 1) {
$this->record[$this->current_field] .= $text;
}
}
function show_menu() {
usort($this->records, array($this, 'resultSort'));
foreach ($this->records as $store) {
echo "<tr>";
$storeURLs = join(', ', $store['storeURL']);
print(
"<td>".$store['Title']."</td>".
"<td>".$store['brand']."</td>".
"<td>".$store['storeName']."</td>".
"<td>".$store['price']."</td>".
"<td>".$storeURL."</td>"
);
echo "</tr>\n";
}
echo "</table>\n";
}
}
echo "<table class=\"xmlresults\">\n";
echo "<tr><td>Title</td>
<td>brand</td>
<td>Store</td>
<td>Price</td>
<td>storeURL</td></tr>";
$my_library = new StoreList ("http://path/to/xml/storefile.xml");
$my_library->show_menu();
echo "</table>";
Is there a way to sort this correctly?
I did try to do a str_replace, but that didn't have any effect. The str_replace code looked like this:
function resultSort($item1, $item2) {
$item1['price'] = str_replace(array(',', ' '), array('.', ''), $item1['price']);
$item2['price'] = str_replace(array(',', ' '), array('.', ''), $item2['price']);
if($item1['price'] == $item2['price']) return 0;
return $item1['price'] < $item2['price'] ? -1 : 1;
}
Does anyone have any suggestions as to how to sort this correctly?