SitePoint Sponsor

User Tag List

Results 1 to 6 of 6
  1. #1
    chown linux:users\ /world Hartmann's Avatar
    Join Date
    Aug 2000
    Location
    Houston, TX, USA
    Posts
    6,455
    Mentioned
    11 Post(s)
    Tagged
    0 Thread(s)

    Question Problem with XML and PHP

    I have the following XML:
    Code:
      <?xml version="1.0" encoding="UTF-8" ?> 
      <current_observation>
       <suggested_pickup>15 minutes after the hour</suggested_pickup> 
      <suggested_pickup_period>60</suggested_pickup_period> 
      <location>Lubbock International Airport, TX</location> 
      <station_id>KLBB</station_id> 
      <latitude>33.40.03N</latitude> 
      <longitude>101.49.17W</longitude> 
      <elevation>NA</elevation> 
      <observation_time>Last Updated on Nov 20, 7:53 pm CST</observation_time> 
      <weather>Fog</weather> 
      <temperature_string>52 F (11 C)</temperature_string> 
      <temp_f>52</temp_f> 
      <temp_c>11</temp_c> 
      <relative_humidity>100</relative_humidity> 
      <wind_string>From the East at 9 MPH</wind_string> 
      <wind_dir>East</wind_dir> 
      <wind_degrees>70</wind_degrees> 
      <wind_mph>9.2</wind_mph> 
      <wind_gust_mph>0</wind_gust_mph> 
      <pressure_string>30.05" (1015.9 mb)</pressure_string> 
      <pressure_mb>1015.9</pressure_mb> 
      <pressure_in>30.05</pressure_in> 
      <dewpoint_string>52 F (11 C)</dewpoint_string> 
      <dewpoint_f>52</dewpoint_f> 
      <dewpoint_c>11</dewpoint_c> 
      <heat_index_string>Not Applicable</heat_index_string> 
      <heat_index_f>Not Applicable</heat_index_f> 
      <heat_index_c>Not Applicable</heat_index_c> 
      <windchill_string>49 F (9 C)</windchill_string> 
      <windchill_f>49</windchill_f> 
      <windchill_c>9</windchill_c> 
      <visibility>0.25 mi.</visibility> 
      
      </current_observation>
    I am using this PHP:
    PHP Code:
    <?php
    $file 
    "KLBB.xml";
    $xml_parser xml_parser_create();

    if ( 
    is_file$file ) )
    {
       
    $fp fopen$file"r" );
       
    $data fread$fpfilesize$file ) );
       
    fclose$fp );
       
    xml_parse_into_struct$xml_parser$data$vals$index );
       
    xml_parser_free$xml_parser );

          echo 
    "<pre>";
          echo 
    "\nVals array\n";
          
    print_r($vals);
          echo 
    "</pre>\n\n";
    }
    ?>
    The print_r statement outputs tons of rows of data, a lot of those being titled CURRENT_OBSERVATION.

    Anyone know why?

    I just want to pull some of the values out of the XML to input into a database. But when I try to pull those fields it does not work. I am guessing it has something to do with the "symptoms" I listed above.

  2. #2
    SitePoint Addict loadx's Avatar
    Join Date
    Jul 2004
    Location
    Melbourne, VIC, Australia
    Posts
    221
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    you need to parse on the selected elements you wany only..there was a tutorial written for an RSS parser written by harry here on SP so maybe you should have a look for that.

    or you could read the xml file into a string and perform simple regex's to get whats between which tag(s).

    and the reason i think it's showing <current_observation> all the time is because every tag is nested inside '<current_observation>' and you are ..though don't quote me on that

    anyways might be worth reading the manual for some refrence.
    http://au2.php.net/manual/en/functio...nto-struct.php

  3. #3
    $this->toCD-R(LP); vinyl-junkie's Avatar
    Join Date
    Dec 2003
    Location
    Federal Way, Washington (USA)
    Posts
    1,524
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Your code is almost correct. Replace this:
    Code:
    print_r($vals);
    with this:
    Code:
    print_r($index);
    Also, have a look at the example on xml_parse_into_struct from the manual.

    Hope this helps.
    Music Around The World - Collecting tips, trade
    and want lists, album reviews, & more
    Showcase your music collection on the Web

  4. #4
    chown linux:users\ /world Hartmann's Avatar
    Join Date
    Aug 2000
    Location
    Houston, TX, USA
    Posts
    6,455
    Mentioned
    11 Post(s)
    Tagged
    0 Thread(s)
    Well I have tried to parse on specific tags but that turned out to be a shot in the dark.

    I tried the print_r($index); and its output is just as abstract.

    Edit:


    Just figured this out... I can use the code I am using but I only want the elements whose parent (current observation) isn't empty.

    Like so:
    PHP Code:
    foreach($index["CURRENT_OBSERVATION"] as $i => $j )
       {
           
    $location $vals[$index["LOCATION"][$i]]["value"];

           if(
    strlen($location) > 0)
           {
            
    $temp_f $vals$index["TEMP_F"][$i] ]["value"];
            
    $condition $vals[$index["WEATHER"][$i]]["value"];
        }
       } 

  5. #5
    SitePoint Enthusiast
    Join Date
    Nov 2004
    Location
    Boston
    Posts
    25
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi

    You should do some reading on dealing with XML data, it will only help you become better at dealing with it!


    Now on to my example....

    I have included (2) files....

    1. xml_get.php

    This is the include file, it contain (2) XML reading functions and (1) other function specific to what you are doing!

    The functions...

    The (2) XML reading functions ( process_xml, get_extended ) can read any XML feed that you send to process_xml(), so save them to you helpful functions library because they will come in handy, many times over! clean_xml() is only used for dealing with the forecast data specific to NOAA current observations!


    Now on to the example...


    script #1 (call it whatever you want, example uses 'forecast.php')

    // this is the script you will call from your browser or include it's code into your current project! If you call it from the browser to test it, do it like so

    http://site_name/forecast.php?id=987654321

    forecast.php

    PHP Code:
    <?

        define 
    'IS_INCLUDED');

        
    // the xml reader functions

        
    include_once ( './xml_get.php' );

        
    $auth '987654321'// only url querys containing this ?id=$auth, can access this script!

        // the feed you want to get (URL TO FEED)

        
    $url 'http://www.nws.noaa.gov/data/current_obs/KLBB.xml';

        
    // the element(s) you want to fetch out of the feed!
        // key => value
        // key = the XML feed element name
        // value = the new name we use to help make things, 
        // easier to manage in the new array we will create!

        
    $change = array ( 
        
    'LOCATION' => 'location'
        
    'STATION_ID' => 'station'
        
    'OBSERVATION_TIME' => 'last'
        
    'WEATHER' => 'cc'
        
    'TEMP_F' => 'ct_f'
        
    'TEMP_C' => 'ct_c'
        
    'RELATIVE_HUMIDITY' => 'humidity'
        
    'WIND_DIR' => 'wind_d'
        
    'WIND_MPH' => 'wind_s'
        
    'PRESSURE_IN' => 'baro_f'
        
    'PRESSURE_MB' => 'baro_c'
        
    'DEWPOINT_F' => 'dew_f'
        
    'DEWPOINT_C' => 'dew_c'
        
    'WINDCHILL_F' => 'wc_f'
        
    'WINDCHILL_C' => 'wc_c'
        
    'VISIBILITY' => 'visibility'
        
    'LATITUDE' => 'lat'
        
    'LONGITUDE' => 'lon' );

        
    // now get and process the feed

        
    if ( !empty ( $_GET['id'] ) && $_GET['id'] == $auth )
        {
            
    $out  file_get_contents $url ) or die (); // die or call a error function then exit();
            
    $out  process_xml $out ); // process this request

            // create the new weather array!
            // with only the data we want!

            
    $forecast clean_xml $out$change );

            
    print_r($forecast); // just print the nice new array
        
    }

    ?>

    This is the include file (xml_get.php)

    PHP Code:
    <?

    // if not called by mom exit!

    if ( !defined 'IS_INCLUDED' ) )
    {
        exit ();
    }

    // this will begin the XML paser
    // it looks for a certain structure and prosess the feed based on what
    // type of structure it has found!


    function process_xml $in )
    {
        
    $xml xml_parser_create 'ISO-8859-1' );
        
    xml_parser_set_option $xmlXML_OPTION_SKIP_WHITE);
        
    xml_parse_into_struct $xml$in$value$name );
        
    xml_parser_free $xml );

        
    $x 0;

        
    $part = array ();

        if ( !empty ( 
    $value[$x]['attributes'] ) )
        {
            
    $part[$value[$x]['tag']][]['ATTRIBUTES'] = $value[$x]['attributes'];
            
    $name = ( count $part[$value[$x]['tag']] ) - );
                
    $part[$value[$x]['tag']][$name] =  array_merge $part[$value[$x]['tag']][$name], get_extended $value$x ) );
        }
        else
        {
            
    $part[$value[$x]['tag']][] = get_extended $value$x );
        }

        return ( 
    $part );
    }

    // this is called by process_xml and it is a recursive function that processes
    // each part of the XML feed, if the array is multi demensional it recalls it's
    // self so that it can merge each multi demensional array into a single element
    // type array! There are a few other ways you can do this, but keeping it generic
    // will allow you to do (2) things, (1) use the least amout of server resources
    // and (2), be able to use these 2 same functions to process any XML feed you want!

    function get_extended $value, &$x )
    {
        
    $node = array ();

          if ( !empty ( 
    $value[$x]['value'] ) )
        {
            
    $node['VALUE'] = $value[$x]['value'];
        }

          while ( ++
    $x count $value ) )
        {
            switch ( 
    $value[$x]['type'] )
            {
                case 
    'cdata':
                    if ( !empty ( 
    $node['VALUE'] ) )
                    {
                        
    $node['VALUE'] .= $value[$x]['value'];
                    }
                    else
                    {
                        
    $node['VALUE'] = $value[$x]['value'];
                    }
                break;
                case 
    'complete':
                    if ( !empty ( 
    $value[$x]['attributes'] ) )
                    {
                        
    $node[$value[$x]['tag']][]['ATTRIBUTES'] = $value[$x]['attributes'];
                              
    $name = ( count $node[$value[$x]['tag']] ) - );
                        
    $node[$value[$x]['tag']][$name]['VALUE'] = !empty ( $value[$x]['value'] ) ? $value[$x]['value'] : '';
                    }
                    else
                    {
                        
    $node[$value[$x]['tag']][]['VALUE'] = !empty ( $value[$x]['value'] ) ? $value[$x]['value'] : '';
                    }
                break;
                case 
    'open':
                    if ( !empty ( 
    $value[$x]['attributes'] ) )
                    {
                        
    $node[$value[$x]['tag']][]['ATTRIBUTES'] = $value[$x]['attributes'];
                        
    $name = ( count $node[$value[$x]['tag']] ) - );
                        
    $node[$value[$x]['tag']][$name] = array_merge $node[$value[$x]['tag']][$name], get_extended $value$x ) );
                    }
                    else
                    {
                        
    $node[$value[$x]['tag']][] = get_extended $value$x );
                    }

                break;
                case 
    'close':
                    return ( 
    $node );
            }
        }
    }


    // the function to build the new array!

    function clean_xml $in$new )
    {
        
    $data = array ();

        foreach ( 
    $new as $k => $v )
        {
            
    $data[$v] = $in['CURRENT_OBSERVATION'][0][$k][0]['VALUE'];
        }

        return ( 
    $data );
    }

    ?>

    Any questions, ask away...

    J!

  6. #6
    chown linux:users\ /world Hartmann's Avatar
    Join Date
    Aug 2000
    Location
    Houston, TX, USA
    Posts
    6,455
    Mentioned
    11 Post(s)
    Tagged
    0 Thread(s)
    Thank you for posting that code but I did figure out what was wrong with my script


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •