Salve a tutti.
Ho creato un piccolo parser XML, questo è il codice
Codice PHP:
<?php
class xmlParser {
function readDocument($file) {
$get = file_get_contents($file);
$content = preg_replace('/<\?xml(.[^>]*)\?>/', '', $get);
return $this->parseStr($content);
}
function parseStr($str) {
preg_replace('/<(.[^>]*)>(.[^<>]*)<\/\\1>/ie', "\$rp = array(trim('\\1') => trim('\\2'));", $str);
foreach($rp as $k => $v) { $kk = $k; $vv = $v; }
if (preg_match('/<(.[^>]*)>/', $vv)) {
$rp[$kk] = $this->parseStr($vv);
}
return $rp;
}
}
?>
il file xml che ho usato è..
codice:
<?xml version="1.0" ?>
<prova>
<prova2>1</prova2>
<prova3>2</prova3>
</prova>
Il problema è molto semplice: legge solo il contenuto dell'ultimo tag nidificato nell'ultimo tag (e così via).
Quello che restituisce è:
Notice: Array to string conversion in C:\Programmi\Apache Group\Apache2\htdocs\xmlparser.php on line 9
Notice: Array to string conversion in C:\Programmi\Apache Group\Apache2\htdocs\xmlparser.php on line 9
Array ( [prova3] => 2 )
Chi mi sa aiutare a correggere il preg_replace?
[edit] Ho modificato il codice con
Codice PHP:
<?php
class xmlParser {
function readDocument($file) {
$get = file_get_contents($file);
$content = preg_replace('/<\?xml(.[^>]*)\?>/', '', $get);
return $this->parseStr($content);
}
function parseStr($str) {
preg_replace('/<(.[^>]*)>(.[^<>]*)<\/\\1>/ie', "\$rp[] = array(trim('\\1') => trim('\\2'));", $str);
if (count($rp) == 1) {
foreach($rp as $ff) {
foreach($f as $k => $v) { $kk = $k; $vv = $v; }
if (preg_match('/<(.[^>]*)>/', $vv)) {
$rp[0][$kk] = $this->parseStr($vv);
}
}
}else{
foreach($rp as $kkk => $vvv) {
foreach($vvv as $k => $v) { $kk = $k; $vv = $vvv; }
if (preg_match('/<(.[^>]*)>/', $vv)) {
$rp[$kkk][$kk] = $this->parseStr($vv);
}
}
}
return $rp;
}
}
?>
In questo caso prende gli elementi in <prova> ma non prende appunto <prova>.