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 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
| <?php
$fichier = 'opcvm_all.xml';
class OPCVMArrayParser
{
/* protected */ var $_parser;
/* protected */ var $_array = array();
/* protected */ var $_curId = -1;
/* protected */ var $_lastTag;
/* public */ function getArrayFromXML()
{
return $this->_array;
}
/* private */ function _init()
{
$this->_parser = xml_parser_create();
xml_parser_set_option($this->_parser, XML_OPTION_CASE_FOLDING, 0);
xml_parser_set_option($this->_parser, XML_OPTION_SKIP_WHITE, 1);
xml_set_object($this->_parser, $this);
xml_set_element_handler($this->_parser, array(&$this, '_startElement'), array(&$this, '_endElement'));
xml_set_character_data_handler($this->_parser, array(&$this, '_characterData'));
}
/* private */ function _parse($data, $is_final = TRUE)
{
$ret = xml_parse($this->_parser, $data, $is_final);
if (!$ret) {
die(xml_error_string(xml_get_error_code($this->_parser)));
}
}
/* public */ function parseFile($fichier)
{
if (is_file($fichier)) {
$fp = fopen($fichier, 'r');
$this->_init();
while ($data = fread($fp, 4096)) {
$this->_parse($data, feof($fp));
}
fclose($fp);
} else {
die("Erreur : '$fichier' est inexistant ou n'est pas un fichier régulier");
}
}
/* public */ function parseString($string)
{
$this->_init();
$this->_parse($string);
}
/* protected */ function _startElement($parser, $name, $attrs)
{
if ($name == 'opcvm' && isset($attrs['id'])) {
$this->_curId = $attrs['id'];
$this->_array[$this->_curId] = array();
} else {
$this->_lastTag = $name;
}
}
/* protected */ function _endElement($parser, $name)
{
if ($name == 'opcvm') {
$this->_curId = -1;
}
}
/* protected */ function _characterData($parser, $data)
{
if ($this->_curId != -1) {
if (!isset($this->_array[$this->_curId][$this->_lastTag])) {
$this->_array[$this->_curId][$this->_lastTag] = $data;
} else {
$this->_array[$this->_curId][$this->_lastTag] .= $data;
}
}
}
/* public */ function __destruct()
{
xml_parser_free($this->_parser);
unset($this->_array);
}
}
$p =& new OPCVMArrayParser();
$p->parseFile($fichier);
$tab = $p->getArrayFromXML();
echo '<pre>' . print_r($tab, TRUE) . '</pre>';
var_dump(trim($tab[4]['date']));
$p->__destruct(); |
Partager