1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
| interface SAXHandler {
public function startElement($parser, $name, Array $attrs);
public function endElement($parser, $name);
public function characterData($parser, $data);
}
class HitHandler implements SAXHandler {
private $cn;
private $phone;
public function __construct() {
echo '<table>'; // A déplacer dans la méthode startElement
}
public function startElement($parser, $name, Array $attrs) {
if ($name == 'HITFIELD') {
if ($attrs['NAME'] == 'cn') {
$this->cn = $attrs['VALUE'];
} else if ($attrs['NAME'] == 'phone') {
$this->phone = $attrs['VALUE'];
}
} else if ($name == 'HIT') {
$this->phone = $this->cn = '';
}
}
public function endElement($parser, $name) {
if ($name == 'HIT' && !empty($this->cn) && !empty($this->phone)) {
printf('<tr><td>%s</td><td>%s</td></tr>', $this->cn, $this->phone);
}
}
public function characterData($parser, $data) {
/* NOP */
}
public function __destruct() {
echo '</table>'; // A déplacer dans la méthode endElement
}
}
abstract class SAXParser
{
protected $parser;
public function __construct(SAXHandler $handler) {
$this->parser = xml_parser_create();
xml_set_object($this->parser, $this);
xml_set_element_handler($this->parser, array($handler, 'startElement'), array($handler, 'endElement'));
xml_set_character_data_handler($this->parser, array($handler, 'characterData'));
}
public function __destruct() {
xml_parser_free($this->parser);
}
}
class SAXFileParser extends SAXParser
{
public function __construct($file, SAXHandler $handler) {
if (is_file($file)) {
parent::__construct($handler);
$fp = fopen($file, 'r');
while ($data = fread($fp, 4096)) {
if (!xml_parse($this->parser, $data, feof($fp))) {
throw new Exception(sprintf("Erreur XML : %s à la ligne %d", xml_error_string(xml_get_error_code($this->parser)), xml_get_current_line_number($this->parser)));
}
}
fclose($fp);
} else {
throw new Exception("Erreur : '$file' est inexistant ou n'est pas un fichier régulier");
}
}
}
try {
$sfp = new SAXFileParser('hits.xml', new HitHandler());
} catch(Exception $e) {
die($e->getMessage());
} |
Partager