Jump to content

Associate array from XML Parse


ars_moriendi

Recommended Posts

Hi all,

I'm trying to parse an XML file into an associate array and having trouble adapting the script I copied ( I know, I know--it's the lowest form of coding, but I need to get this done and I haven't been getting a lot of sleep lately).

This is my script:

$name="";
$stack = array();

if (! ($xmlparser = xml_parser_create()) )
{ 
   die ("Cannot create parser");
}

function start_tag($parser, $name, $attribs) {
   	echo "Current tag : ".$name."<br />";
   	if (is_array($attribs)) {
      echo "Attributes : <br />";
      while(list($key,$val) = each($attribs)) {
         echo "Attribute ".$key." has value ".$val."<br />";
       }
    }
}

function end_tag($parser, $name) {
   echo "Reached ending tag ".$name."<br /><br />";
}
function tag_contents($parser, $data) {
global $stack;
//NUMERIC ARRAY
array_push($stack, $data); 
//ASSOCIATIVE ARRAY???
/* $stack["$name"]="data";*/
   	echo "Contents : ".$data."<br />";
}

xml_set_element_handler($xmlparser, "start_tag", "end_tag");
xml_set_character_data_handler($xmlparser, "tag_contents");

$filename = "http://www.blahblah.com/rss.rss";
if (!($fp = fopen($filename, "r"))) { 
die("cannot open ".$filename); 
}

while ($data = fread($fp, 4096)){
   $data=eregi_replace(">"."[[:space:]]+"."<","><",$data);
   if (!xml_parse($xmlparser, $data, feof($fp))) {
      $reason = xml_error_string(xml_get_error_code($xmlparser));
      $reason .= xml_get_current_line_number($xmlparser);
      die($reason);
   }
}
xml_parser_free($xmlparser);

 

I know why stack["$name"]="data"; doesn't work, but my brain is melting and when I try and figure out the logic to do it properly, I get stuck.

Any ideas?

Thanks for your help.

-Erin

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.