XML question

Could anyone teach me how to get value from an XML string ?

I have this long xml string :

<Order>
  <Date "October 12, 2004" />
  <OrderNumber "12345" />
  <Items>
     <ItemName>Box</ItemName>
     <Quantity>1</Quantity>
  </Items>
  <Info>
     <Name>Eric</Name>
     <Address>Here</Address>
  </info>
</Order>

Basically I want to move those information into a MySQL database. The MySQL things are not a problem. But I dont know how to get the XML values. I searched in php.net, but seems there are so many functions and ways to do this. If you could give me one simple example that works, it would be enough.

I use PHP 4.3.3 on Linux btw.

Thanks
muis2002Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

KvdnBergCommented:
There's plenty of tutorials out there that I think can help you out. Here's one : http://www.zend.com/zend/tut/tutbarlach.php
And here's one one expat, http://www.zend.com/zend/art/parsing.php, the PHP xml parser.
Hope this helps!
0
muis2002Author Commented:
I got this code below working. But it has a problem, if there are same ELEMENT NAME in the same LEVEL, it will only print the last element.

For example :

<Data>
     <Items>One</Items>
     <Items>Two</Items>
</Data>

It will only process the last <Item>

Anyone know how to fix this ?

<?php

// Display the print_r() output in a readable format
echo '<PRE>';

// Array to store current xml path
$ary_path = array();

// Array to store parsed data
$ary_parsed_file = array();

// Starting level - Set to 0 to display all levels. Set to 1 or higher
// to skip a level that is common to all the fields.
$int_starting_level = 1;

// what are we parsing?
$xml_file = 'label.xml';

// declare the character set - UTF-8 is the default
$type = 'UTF-8';

// create our parser
$xml_parser = xml_parser_create($type);

// set some parser options
xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, true);
xml_parser_set_option($xml_parser, XML_OPTION_TARGET_ENCODING, 'UTF-8');

// this tells PHP what functions to call when it finds an element
// these funcitons also handle the element's attributes
xml_set_element_handler($xml_parser, 'startElement','endElement');

// this tells PHP what function to use on the character data
xml_set_character_data_handler($xml_parser, 'characterData');

if (!($fp = fopen($xml_file, 'r'))) {
   die("Could not open $xml_file for parsing!\n");
}

// loop through the file and parse baby!
while ($data = fread($fp, 4096)) {
   if (!($data = utf8_encode($data))) {
       echo 'ERROR'."\n";
   }
   if (!xml_parse($xml_parser, $data, feof($fp))) {
       die(sprintf( "XML error: %s at line %d\n\n",
       xml_error_string(xml_get_error_code($xml_parser)),
       xml_get_current_line_number($xml_parser)));
   }
}

xml_parser_free($xml_parser);

// Display the array
print_r($ary_parsed_file);

// This function is called for every opening XML tag. We
// need to keep track of our path in the XML file, so we
// will use this function to add the tag name to an array
function startElement($parser, $name, $attrs=''){

   // Make sure we can access the path array
   global $ary_path;
   
   // Push the tag into the array
   array_push($ary_path, $name);

   }

// This function is called for every closing XML tag. We
// need to keep track of our path in the XML file, so we
// will use this function to remove the last item of the array.
function endElement($parser, $name, $attrs=''){

   // Make sure we can access the path array
   global $ary_path;
   
   // Push the tag into the array
   array_pop($ary_path);

   }

// This function is called for every data portion found between
// opening and closing tags. We will use it to insert values
// into the array.
function characterData($parser, $data){
   
   // Make sure we can access the path and parsed file arrays
   // and the starting level value
   global $ary_parsed_file, $ary_path, $int_starting_level;

   // Remove extra white space from the data (so we can tell if it's empty)
   $str_trimmed_data = trim($data);
   
   // Since this function gets called whether there is text data or not,
   // we need to prevent it from being called when there is no text data
   // or it overwrites previous legitimate data.
   if (!empty($str_trimmed_data)) {

       // Build the array definition string
       $str_array_define = '$ary_parsed_file';
               
       // Add a [''] and data for each level. (Starting level can be defined.)
       for ($i = $int_starting_level; $i < count($ary_path); $i++) {
       
           $str_array_define .= '[\'' . $ary_path[$i] . '\']';
           
           }
       
       // Add the value portion of the statement
       $str_array_define .= " = '" . $str_trimmed_data . "';";
       
       // Evaluate the statement we just created
       eval($str_array_define);
       
       // DEBUG
       //echo "\n" . $str_array_define;
       
       } // if

   }

?>
0
compustarsgCommented:
hi, the code you are try may work with little tweak. but here iam giving other sample using domxml, xpath which i think will work.

<?php

$xml_file = 'label.xml';

$fp = fopen($xml_file, "r");
$contents = fread($fp, filesize($xml_file));

if (!$dom =  domxml_open_mem($contents)) {
  echo "Error while parsing the document\n";
  exit;
}

// using xpath
$ctx = xpath_new_context($dom);
$xo = xpath_eval($ctx,"/Order");

// parse xml and get nodes into array
foreach($xo->nodeset as $key=>$val)
{
   $arritems = array();
   $arrinfo = array();

   $arr1 = $val->child_nodes();

   foreach($arr1 as $key1=>$val1)
   {
      if ($val1->node_name() == "Items") {
          $arr2 = $val1->child_nodes();

          foreach($arr2 as $key2=>$val2) {
             if ($val2->node_name() != "#text") {
               //echo $val2->node_name() . "-" . $val2->get_content()."<br>";    
               $arr3[$val2->node_name()] = $val2->get_content();
             }
          }
          array_push($arritems, $arr3);
      }

      if ($val1->node_name() == "Info") {
          $arr2 = $val1->child_nodes();

          foreach($arr2 as $key2=>$val2) {    
             $arr3[$val2->node_name()] = $val2->get_content();
          }
          array_push($arrinfo, $arr3);
      }
   
      $arrorder[$key] = array("Items"=>$arritems,"Info"=>$arrinfo);
   }
   
}

// output
foreach($arrorder as $key=>$val){
    echo "Order<br><br>";
    $items = $val["Items"];
    foreach($items as $key1=>$val1) {
        echo "ItemName"."-".$val1["ItemName"]."<br>";
        echo "Quantity"."-".$val1["Quantity"]."<br>";        
    }

    $info = $val["Info"];
    foreach($info as $key1=>$val1) {
        echo "Name"."-".$val1["Name"]."<br>";
        echo "Address"."-".$val1["Address"]."<br>";        
    }
    echo "<br>";
}
?>

label.xml
---------------------
<?xml version="1.0" encoding="UTF-8"?>
<Order>
  <Date Value="October 12, 2004"/>
  <OrderNumber Value="12345" />
  <Items>
     <ItemName>Box</ItemName>
     <Quantity>1</Quantity>
  </Items>
  <Items>
     <ItemName>Box1</ItemName>
     <Quantity>2</Quantity>
  </Items>
  <Info>
     <Name>Eric</Name>
     <Address>Here</Address>
  </Info>
</Order>
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Web Languages and Standards

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.