XML question

Posted on 2004-11-21
Last Modified: 2013-11-19
Could anyone teach me how to get value from an XML string ?

I have this long xml string :

  <Date "October 12, 2004" />
  <OrderNumber "12345" />

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, 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.

Question by:muis2002
    LVL 3

    Expert Comment

    There's plenty of tutorials out there that I think can help you out. Here's one :
    And here's one one expat,, the PHP xml parser.
    Hope this helps!

    Author Comment

    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 :


    It will only process the last <Item>

    Anyone know how to fix this ?


    // 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",


    // Display the array

    // 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


    // 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
           // DEBUG
           //echo "\n" . $str_array_define;
           } // if


    LVL 1

    Accepted Solution

    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.


    $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";

    // 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>";

    <?xml version="1.0" encoding="UTF-8"?>
      <Date Value="October 12, 2004"/>
      <OrderNumber Value="12345" />

    Featured Post

    What Security Threats Are You Missing?

    Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

    Join & Write a Comment

    I found this questions asking how to do this in many different forums, so I will describe here how to implement a solution using PHP and AJAX. The logical flow for the problem should be: Write an event handler for the first drop down box to get …
    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…
    Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
    The viewer will learn how to count occurrences of each item in an array.

    728 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

    Need Help in Real-Time?

    Connect with top rated Experts

    17 Experts available now in Live!

    Get 1:1 Help Now