/    Sign up×
Community /Pin to ProfileBookmark

concverting XML to Array (in eassy way)

hey all
I was looking at the docs and im very confused,
can some one give me sample code that converts XML file into array?

I found rhis script but it create some wired array that i can not really output data with “echo $reply[0][0]; “

So maybe some one can help?

Thanks a lot!

[code=php]
<?php
$p =& new xmlParser();
$p->parse(“xmlfile.xml”);
echo “<pre>”;
print_r($p->output);
echo “</pre>”;
$reply[]=$p->output;
echo “————–<br>”;
echo $reply[0][0];
//echo $p->output[0][1];

class xmlParser{
var $xml_obj = null;
var $output = array();
var $attrs;

function xmlParser(){
$this->xml_obj = xml_parser_create();
xml_set_object($this->xml_obj,$this);
xml_set_character_data_handler($this->xml_obj, ‘dataHandler’);
xml_set_element_handler($this->xml_obj, “startHandler”, “endHandler”);
}

function parse($path){
if (!($fp = fopen($path, “r”))) {
die(“Cannot open XML data file: $path”);
return false;
}

while ($data = fread($fp, 4096)) {
if (!xml_parse($this->xml_obj, $data, feof($fp))) {
die(sprintf(“XML error: %s at line %d”,
xml_error_string(xml_get_error_code($this->xml_obj)),
xml_get_current_line_number($this->xml_obj)));
xml_parser_free($this->xml_obj);
}
}

return true;
}

function startHandler($parser, $name, $attribs){
$_content = array();
$_content[‘name’] = $name;
if(!empty($attribs))
$_content[‘attrs’] = $attribs;
array_push($this->output, $_content);
}

function dataHandler($parser, $data){
if(!empty($data) && $data!=”n”) {
$_output_idx = count($this->output) – 1;
$this->output[$_output_idx][‘content’] .= $data;
}
}

function endHandler($parser, $name){
if(count($this->output) > 1) {
$_data = array_pop($this->output);
$_output_idx = count($this->output) – 1;
$add = array();
if(!$this->output[$_output_idx][‘child’])
$this->output[$_output_idx][‘child’] = array();
array_push($this->output[$_output_idx][‘child’], $_data);
}
}
}
?>
[/code]

to post a comment
PHP

0Be the first to comment 😎

×

Success!

Help @alexus spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.25,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...