Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

XML question

Posted on 2004-11-21
5
Medium Priority
?
285 Views
Last Modified: 2013-11-19
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
0
Comment
Question by:muis2002
3 Comments
 
LVL 3

Expert Comment

by:KvdnBerg
ID: 12637840
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
 

Author Comment

by:muis2002
ID: 12639739
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
 
LVL 1

Accepted Solution

by:
compustarsg earned 400 total points
ID: 12641473
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

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
The viewer will the learn the benefit of plain text editors and code an HTML5 based template for use in further tutorials.
Suggested Courses

580 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question