[Php-it] Leggere file xml, come si fa?
Giginiello
giginiello at fastwebnet.it
Fri Jul 6 15:46:59 CEST 2007
Ciao a tutti,
avrei bisogno di uno script che legga un file xml e lo riproduca paro paro
in output. In parole povere ricevo in input un URL del tipo:
http://www.miosito.com/miofile.xml e dovrei riprodurre in output il codice
XML senza nessuna elaborazione particolare.
Anche per capire come funzionano vorrei utilizzare le funzioni dell'xml
parser integrato (xml_parser_create(), xml_set_element_handler, ecc.)
Ho cercato in rete ed ho trovato parecchia roba buggata e comunque nessuna
che faccia al caso mio, ho provato a modificare il seguente codice ma non
legge gli attributi e non chiude i nodi annidati:
<?php
$insideitem = false;
$tag = "";
function startElement($parser, $name, $attrs) {
global $insideitem, $tag;
print "<".$name.">";
if ($insideitem) {
$tag = $name;
}
elseif (strtolower($name) == "primo elemento") {
$insideitem = true;
}
}
function endElement($parser, $name) {
global $insideitem, $tag;
print "</".$tag.">";
$insideitem = false;
}
function characterData($parser, $data) {
global $insideitem, $tag;
print $data;
}
$xml_parser = xml_parser_create();
xml_set_element_handler($xml_parser, "startElement", "endElement");
xml_set_character_data_handler($xml_parser, "characterData");
// Carico la mia sorgente XML
$fp = fopen("myFile.xml","r") or die("Error reading XML data.");
while ($data = fread($fp, 4096)) {
xml_parse($xml_parser, $data, feof($fp)) or die(sprintf("XML error: %s at
line %d", xml_error_string(xml_get_error_code($xml_parser)),
xml_get_current_line_number($xml_parser)));
}
fclose($fp);
xml_parser_free($xml_parser);
?>
Sicuramente qualcuno ha già affrontato il problema, mi date una mano?
Ah, la versione di PHP che uso è la 4.4.4
Grazie.
More information about the Php-it
mailing list