Jump to content

No data output with SimpleXML


Texan78
Go to solution Solved by Barand,

Recommended Posts

Hello, I am apparently missing something and could use another set of eyes. I am parsing an XML file with simpleXML and I have done it several times with no issues and this one is pretty straight forward and should be easy but I am missing something. It displays the tables but the tables are empty. So to test I echo one of the variables and nothing shows. It's strange that the tables are outputting but with no data.

 

 

Here is example of the XML I am parsing.

<?xml version="1.0" encoding="ISO-8859-1"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#">
<channel>
<atom:link href="http://www.spotternetwork.org/feeds/rss-reports.xml" rel="self" type="application/rss+xml" />
<title>Spotter Network Reports</title>
<description>The last 3 hours of weather reports from the SN community</description>
<link>http://www.spotternetwork.org</link>
<item><title>Hail Size: 0.88" (Nickel) near 2 miles WSW of COLLYER, KS</title>
<geo:lat>39.024000000000000</geo:lat>
<geo:long>-100.148000000000000</geo:long>
<description>"(Reported By) Daniel Shaw (Time) 2013-05-08 01:45:00 UTC (Notes) Falling now."</description>

<link>http://www.spotternetwork.org/google.php</link>
<guid>http://www.spotternetwork.org/report.php?id=13685</guid>
</item>
<item><title>Hail Size: 1.00" (Quarter) near 0 miles N of QUINTER, KS</title>
<geo:lat>39.070000000000000</geo:lat>
<geo:long>-100.235000000000000</geo:long>
<description>"(Reported By) Daniel Shaw (Time) 2013-05-08 01:36:00 UTC (Notes) Fell 1min ago."</description>
<link>http://www.spotternetwork.org/google.php</link>
<guid>http://www.spotternetwork.org/report.php?id=13684</guid>

</item>
<item><title>Hail Size: 0.75" (Penny) near 8 miles SSW of GREENSBURG, KS</title>
<geo:lat>37.498316666666700</geo:lat>
<geo:long>-99.320266666666700</geo:long>
<description>"(Reported By) John Guyton (Time) 2013-05-08 00:56:00 UTC (Notes) A few pennys mixed in with pea and dime size hail. Moderate amount has fallen in the last 5 minutes and continues to fall."</description>
<link>http://www.spotternetwork.org/google.php</link>
<guid>http://www.spotternetwork.org/report.php?id=13683</guid>
</item>
</channel>
</rss>
  

What am I missing?

-Thanks

 

Here is the example of the code I am using to parse it.

$data = "http://www.spotternetwork.org/feeds/rss-reports.xml";
$xml = simplexml_load_file($data);

foreach($xml->channel->item as $item){

    $title = $item['title'];
    $desc = $item['description'];
    
echo $desc;
        
// construct data for table display
  $tData .= '<table style="width: 100%; margin: 0px auto; background-color:<?php print ($bkgColor); ?>;" cellpadding="0" cellspacing="0">
 <tbody><tr>
  <td style="'.$tbrdr.';'.$sbrdr.'; padding: 2px 0px 2px 6px;  background-image:url('.$imagesDir.'headerbgd2.gif); color: '.$dtColor.'"><b>'.$title.'</b>
 </td>
 </tr>
 <tr>
  <td class="opacity" style="'.$sbrdr.'; padding: 6px 0px 0px 6px; background-color: '.$bc.';">'.$desc.'</td>
 </tr>
 <tr>
  <td class="opacity" style="'.$sbrdr.'; line-height:5px; background-color:'.$bc.'"> </td>
 </tr>
 <tr>
  <td class="opacity" style="'.$sbrdr.'; '.$bbrdr.'; padding: 2px 6px 6px 6px; background-color:'.$bc.'">'.$desc.'</td></tr></tbody></table>
<table style="margin-bottom: 5px;" border="0" cellpadding="0" cellspacing="0" width="100%"><tbody><tr><td><img alt="" src="images/1pixel.gif" border="0" height="7" width="7"></td><td class="shadow-mid" width="100%"><img alt="" src="images/1pixel.gif" border="0" height="7" width="7"></td><td><img alt="" src="images/1pixel.gif" border="0" height="7" width="7"></td></tr></tbody></table>';

        
}

?>

Link to comment
Share on other sites

Never mind scratch this post above. That feed didn't have the data I needed. The feed that had the data I needed I was able to use my other method and was able to get it to work.

 

BUT....

 

This feed has something I haven't dealt with before and not sure how to parse it. The feed has element attributes which is not a big deal but some of the attributes of the element are like this....

tornado="0" funnelcloud="0" wallcloud="0" rotation="0" hail="1" wind="0" flood="0" flashflood="0" other="0"

So basically if there is a 1 it will output that data. So how do I parse that so it outputs the listed one? I am thinking I need an array maybe? If so any examples so I can get an idea?

 

-Thanks

Link to comment
Share on other sites

Are those attributes indicating what type of data is contained by the element?

 

Yes, exactly. It is just one element and those are all the attributes within that element. The output is based on the value of 1. I.E. if it's hail="1" then the output would be Hail but, if you parse the attribute the output would be 1. So I think I need a switch based on the value to get the text output. This is what I have come up with.

$attrs = array();
            foreach($report->attributes() as $a => $b) {
    $attrs[$a] = $b;
}

$value = array_search('1', $attrs);

switch ($value) {
    case 'tornado':
        echo "Tornado";
        break;
    case 'funnelcloud':
        echo "Funnel Cloud";
        break;
    case 'wallcloud':
        echo "Wall Cloud";
        break;
    case 'rotation':
        echo "Rotation";
        break; 
    case 'hail':
        echo "Hail";
        break; 
    case 'wind':
        echo "Wind";
        break;
    case 'flood':
        echo "Flood";
        break;  
    case 'flashflood':
        echo "Flash Flood";
                             
}   

I really can't test it at the moment since the feed is empty at the moment. So am I on the right track or do you have any suggestions?

 

-Thanks

Link to comment
Share on other sites

    $title = $item->title;
    $desc = $item->description;

not

    $title = $item['title'];
    $desc = $item['description'];

title and description are not attributes

 

 

Thank you, I tried that suggestion but I am still getting nothing. I have tried it several other ways too and I get nothing.

<?php
#######################################################################################
#
#  SPC TORNADO/SEVERE THUNDERSTORM WATCHES
#  version 1.00
#
#  This program is free and no license is required.
#
#
#  mesquiteweather.net
#
#######################################################################################

////  SETTINGS  ////

// Change colors
$bkgColor                                       = '#d4d4d4';     // Background color   Examples:  "gray"  "#CCC"   "#CCCCCC"
$bc                                             = '#EEEEEE';  // Background color of table cells
$dtColor                                        = '#FFF';     // Date & time color  Examples:   "#FC0"   "#FFCC00"   "white"
$width                                          = '100%';

////  END OF SETTINGS  ////

#######################################################################################

ini_set('display_errors','1');

## Start Configurable data ##

//Set path to data file
$data                                           = "xml/spcwwrss.xml";

## End Configurable data ##

// overrides from the Carter Lake Settings.php file (if applicable)
global $SITE;
if(isset($SITE['cacheFileDir'])) {$cacheFileDir = $SITE['cacheFileDir']; }
if (isset($SITE['imagesDir']))   {$imagesDir    = $SITE['imagesDir'];}
if(isset ($SITE['tz']))          {$ourTZ        = $SITE['tz'];}
if(!function_exists('date_default_timezone_set'))
{
    putenv("TZ                                  = " . $ourTZ);
}
else
{
    date_default_timezone_set("$ourTZ");
}

// get path info & protect for cross-site scripting vulnerability
$sri                                            = ($_SERVER['REQUEST_URI']) ? str_replace('#SA', '', htmlspecialchars(strip_tags($_SERVER['REQUEST_URI']))) : '';

// set borders
$bbrdr                                          = 'border-bottom:thin solid black';       // bottom
$lbrdr                                          = 'border-left:thin solid black';         // left
$rbrdr                                          = 'border-right:thin solid black';        // right
$tbrdr                                          = 'border-top:thin solid black';          // top
$sbrdr                                          = 'border-right:thin solid black; '.
                                                  'border-left:thin solid black';         // side

//Define table to display after each storm report
$afterTable                                     = "<table style='margin-bottom: 5px;' border='0' cellpadding='0' cellspacing='0' width='100%'><tbody><tr><td><img alt='' src='images/1pixel.gif' border='0' height='7' width='7'></td><td class='shadow-mid' width='100%'><img alt='' src='images/1pixel.gif' border='0' height='7' width='7'></td><td><img alt='' src='images/1pixel.gif' border='0' height='7' width='7'></td></tr><tbody></table>\n";

// Let's assign the table some styles
   $noMessageStyle                              = "width:{$width}; text-align:center; margin:0px auto; background-color:{$bkgColor};";
   $td1Style                                    = "{$tbrdr};{$sbrdr}; padding:2px 0px 2px 6px;  background-image:url({$imagesDir}headerbgd2.gif); color:{$dtColor};";
   $td2Style                                    = "{$sbrdr}; padding:6px 0px 0px 6px;";
   $td3Style                                    = "{$sbrdr}; line-height:5px;";
   $td4Style                                    = "{$sbrdr}; {$bbrdr}; padding: 2px 6px 6px 6px;";


//Set message to display if there were not report
    $noStormMessage                                     .= "<table style='{$noMessageStyle}' cellpadding='0' cellspacing='0'>\n";
    $noStormMessage                                     .= "<tbody>\n";
    $noStormMessage                                     .= "  <tr><td style='{$td1Style}'>SPC TORNADO/SEVERE THUNDERSTORM WATCHES</td></tr>\n";
    $noStormMessage                                     .= "  <tr><td style='{$td4Style}'>There are currently no active severe thunderstorm or tornado watches</td></tr>\n";
    $noStormMessage                                     .= "</tbody>\n";
    $noStormMessage                                     .= "</table>\n";
    $noStormMessage                                     .= $afterTable;


//Set initial output to false
$tData                                          = false;
$entries                                        = simplexml_load_file($data);
if(count($entries)):
    //Registering NameSpace
    $entries->registerXPathNamespace('prefix', 'http://www.w3.org/2005/Atom');
    $result                                     = $entries->xpath("//prefix:item");

    foreach ($result as $entry):
        $title                                  = $item['title'];
        $description                            = $item['description'];

// Let's assign the table some styles
   $tableStyle                                  = "width: 100%; margin:0px auto; background-color:{$bkgColor};";
   $td1Style                                    = "{$tbrdr};{$sbrdr}; padding:2px 0px 2px 6px;  background-image:url({$imagesDir}headerbgd2.gif); color:{$dtColor};";
   $td2Style                                    = "{$sbrdr}; padding:6px 0px 0px 6px; background-color:{$alertColor};";
   $td3Style                                    = "{$sbrdr}; line-height:5px; background-color:{$alertColor};";
   $td4Style                                    = "{$sbrdr}; {$bbrdr}; padding: 2px 6px 6px 6px; background-color:{$alertColor};";

// construct data for table display
    $tData                                     .= "<table style='{$tableStyle}' cellpadding='0' cellspacing='0'>\n";
    $tData                                     .= "<tbody>\n";
    $tData                                     .= "  <tr><td style='{$td1Style}'><b>{$title}</b></td></tr>\n";
    $tData                                     .= "  <tr>\n";
    $tData                                     .= "    <td style='{$td2Style}'> </td>\n";
    $tData                                     .= "  </tr>\n";
    $tData                                     .= "  <tr><td style='{$td3Style}'> </td></tr>\n";
    $tData                                     .= "  <tr><td style='{$td4Style}'>Issued For: <b>{$description}</b></td></tr>\n";
    $tData                                     .= "</tbody>\n";
    $tData                                     .= "</table>\n";
    $tData                                     .= $afterTable;

       endforeach;
endif;

//If no storms were in the source, set no storm message
if(!$tData)
{
    $tData                                      = $noStormMessage;
}

echo $tData;

?>

Here is a link to the test XML I am using.

 

http://www.mesquiteweather.net/xml/spcwwrss.xml

 

What am I missing?

Link to comment
Share on other sites

 

Try using these three lines instead of yours

    $result                                     = $entries->xpath("//item");

    foreach ($result as $entry):
        $title                                  = $entry->title;
        $description                            = $entry->description;

 

 

Ah I see the difference. It doesn't use //prefix because the element isn't a namespace right? That's strange because I have used it that way before on elements that weren't namespaces. I had even tried it exactly how you had it but, it had the //prefix included. Guess it just depends on the way the XML is formatted? Well you learn something everyday. It works perfectly now. Thank you for your help.

Link to comment
Share on other sites

Ah I see the difference. It doesn't use //prefix because the element isn't a namespace right? … Guess it just depends on the way the XML is formatted? Well you learn something everyday.

That's right, the <item> elements that you want are not within a namespace so there is no need to register a prefix nor use that prefix in the XPath query.

 

If you decided not to use XPath at all, an alternative would be like:

 

foreach ($entries->channel->item as $entry) …
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.