SimpleXML PHP Parsing [duplicate] - php

This question already has an answer here:
Closed 10 years ago.
It IS a duplicate, just not for the question that is was closed for.
Finally found the answer, even here on SO.
Actual Duplicate: PHP SimpleXML Namespace Problem
EDIT: If you read the question closely, you will see it is NOT a duplicate of PHP namespace simplexml problems. The answer from the 'possible duplicate' is not the answer to my question.
Again:
I have no problem with $value = $record->children('cap', true)->$title;.(which is all the 'possible duplicate' answers)
I have a problem when there are other tags inside the tag with the colon.
<tag:something>hello</tag:something> //I parse out hello (this is the 'duplicate questions' answer that I don't need answered)
<tag:something>
<stuff>hello</stuff> //I cannot grab this. Explanation below.
</tag:something>
END of edit.
ORIGINAL question:
I cannot get the data inside the tag <value> in the XML located at http://alerts.weather.gov/cap/us.php?x=1 (sample of XML below).
The problem is at:
$array[] = $record->children($tag_cap, true)->$tag_geocode->$tag_value;
This is the only data I cannot grab, I have verified that all the other data other than $array[4] is grabbed.
There is just a problem getting data from tags when the parent tag is in the form <cap:something>. For example:
I can get 100 when it is like <cap:something>100</cap:something>. But I cant get 100 if it was like <cap:something><value>100</value></cap:something>.
Piece of the XML:
<?xml version = '1.0' encoding = 'UTF-8' standalone = 'yes'?>
<feed
xmlns = 'http://www.w3.org/2005/Atom'
xmlns:cap = 'urn:oasis:names:tc:emergency:cap:1.1'
xmlns:ha = 'http://www.alerting.net/namespace/index_1.0'
>
<!-- http-date = Tue, 30 Oct 2012 06:34:00 GMT -->
<id>http://alerts.weather.gov/cap/us.atom</id>
<logo>http://alerts.weather.gov/images/xml_logo.gif</logo>
<generator>NWS CAP Server</generator>
<updated>2012-10-30T14:34:00-04:00</updated>
<author>
<name>w-nws.webmaster#noaa.gov</name>
</author>
<title>Current Watches, Warnings and Advisories for the United States Issued by the National Weather Service</title>
<link href='http://alerts.weather.gov/cap/us.atom'/>
<entry>
<id>http://alerts.weather.gov/cap/wwacapget.php?x=AK124CCADA8120.BlizzardWarning.124CCAE7BFC0AK.AFGWSWNSB.d32adb45b5c82ec5e486c4cfb96d3fb6</id>
<updated>2012-10-30T05:20:00-08:00</updated>
<published>2012-10-30T05:20:00-08:00</published>
<author>
<name>w-nws.webmaster#noaa.gov</name>
</author>
<title>Blizzard Warning issued October 30 at 5:20AM AKDT until October 31 at 6:00AM AKDT by NWS</title>
<link href='http://alerts.weather.gov/cap/wwacapget.php?x=AK124CCADA8120.BlizzardWarning.124CCAE7BFC0AK.AFGWSWNSB.d32adb45b5c82ec5e486c4cfb96d3fb6'/>
<summary>...BLIZZARD WARNING IN EFFECT UNTIL 6 AM AKDT WEDNESDAY... THE NATIONAL WEATHER SERVICE IN FAIRBANKS HAS ISSUED A BLIZZARD WARNING...WHICH IS IN EFFECT UNTIL 6 AM AKDT WEDNESDAY. * VISIBILITY...NEAR ZERO IN SNOW AND BLOWING SNOW. * WINDS...WEST 35 MPH GUSTING TO 50 MPH. * SNOW...ACCUMULATION 3 INCHES THROUGH TONIGHT.</summary>
<cap:event>Blizzard Warning</cap:event>
<cap:effective>2012-10-30T05:20:00-08:00</cap:effective>
<cap:expires>2012-10-30T16:00:00-08:00</cap:expires>
<cap:status>Actual</cap:status>
<cap:msgType>Alert</cap:msgType>
<cap:category>Met</cap:category>
<cap:urgency>Expected</cap:urgency>
<cap:severity>Severe</cap:severity>
<cap:certainty>Likely</cap:certainty>
<cap:areaDesc>Eastern Beaufort Sea Coast</cap:areaDesc>
<cap:polygon></cap:polygon>
<cap:geocode>
<valueName>FIPS6</valueName>
<value>002185</value>
<valueName>UGC</valueName>
<value>AKZ204</value>
</cap:geocode>
<cap:parameter>
<valueName>VTEC</valueName>
<value>/X.NEW.PAFG.BZ.W.0013.121030T1320Z-121031T1400Z/</value>
</cap:parameter>
</entry>
...//rest of XML...
PHP Code:
ini_set('display_errors','1');
$alert_url = 'http://alerts.weather.gov/cap/us.php?x=1';
$alert_string_xml = file_get_contents($alert_url);
$alert_simple_xml_object = simplexml_load_string($alert_string_xml);
$count = 0;
$tag_entry = 'entry';
$tag_summary = 'summary';
$tag_cap = 'cap';
$tag_event = 'event';
$tag_certainty = 'certainty';
$tag_areaDesc = 'areaDesc';
$tag_geocode = 'geocode';
$tag_value = 'value';
foreach ($alert_simple_xml_object->$tag_entry as $record)
{
$count++;
$array = array();
$array[] = $record->$tag_summary;
$array[] = $record->children($tag_cap, true)->$tag_event;
$array[] = $record->children($tag_cap, true)->$tag_certainty;
$array[] = $record->children($tag_cap, true)->$tag_areaDesc;
$array[] = $record->children($tag_cap, true)->$tag_geocode->$tag_value;
//$array[] = $record->children($tag_cap, true)->$tag_geocode->$tag_value[0]; //doesnt work either
echo $array[4]; //nothing is echoed
}
MOST CURRENT ATTEMPT:
I read more on namespaces and understand them better. I even tried what I thought was a better solution:
//inside the above foreach loop
$namespaces = $record->getNameSpaces(true);
$caap = $record->children($namespaces['cap']);
echo $caap->event; //works (but the first way works too)
echo $caap->geocode->value; //(STILL does not work. Nothing is echoed)
I don't understand why I cannot grab any data from children tags that have a parent tag that includes a namespace.

cap:stuff is the root, so you would access the elements as:
$xml = simplexml_load_string($your_xml);
$value_name_0 = $xml->valueName[0];
$value_0 = $xml->value[0];
$value_name_1 = $xml->valueName[1];
$value_1 = $xml->value[1];

You are probably looking for this function. There are 2 examples, which should be enough to solve your problem

The problem you are facing is not that visible if you have errors and warnings disabled:
namespace error : Namespace prefix cap on stuff is not defined
If you would have errors enable you would see that message. Because simplexml is not able to parse the namespace prefix cap properly, it will be dropped.
Therefore you access it directly:
$xml->stuff->value[1]
And similar. Consider the following code-example (demo:
$xml = simplexml_load_string('<entry>
<cap:stuff>
<valueName>aaa</valueName>
<value>000</value>
<valueName>bbb</valueName>
<value>111</value>
</cap:stuff>
</entry>');
echo "\nResult:", $xml->stuff->value[1], "\n\n";
echo "XML:\n", $xml->asXML();
It demonstrates the error message as well what is in $xml after loading the XML string by outputting it:
Warning: simplexml_load_string(): namespace error : Namespace prefix cap on \
stuff is not defined on line 10
Warning: simplexml_load_string(): <cap:stuff> on line 10
Warning: simplexml_load_string(): ^ on line 10
Result:111
XML:
<?xml version="1.0"?>
<entry>
<stuff>
<valueName>aaa</valueName>
<value>000</value>
<valueName>bbb</valueName>
<value>111</value>
</stuff>
</entry>
If you smell that something should work but it isn't, it is always necessary to look closer. One option is to echo the string again as XML to see what simplexml has parsed, the other is to enable error reporting and looking for warnings and error, they often contain further information.

Related

PHP not returning full XML file contents [duplicate]

I'm trying to read an RSS feed from Flickr but it has some nodes which are not readable by Simple XML (media:thumbnail, flickr:profile, and so on).
How do I get round this? My head hurts when I look at the documentation for the DOM. So I'd like to avoid it as I don't want to learn.
I'm trying to get the thumbnail by the way.
The solution is explained in this nice article. You need the children() method for accessing XML elements which contain a namespace. This code snippet is quoted from the article:
$feed = simplexml_load_file('http://www.sitepoint.com/recent.rdf');
foreach ($feed->item as $item) {
$ns_dc = $item->children('http://purl.org/dc/elements/1.1/');
echo $ns_dc->date;
}
With the latest version, you can now reference colon nodes with curly brackets.
$item->{'itunes:duration'}
You're dealing with a namespace? I think you need to use the ->children method.
$ns_dc = $item->children('http://namespace.org/');
Can you provide a snippet with the xml declaration?
An even simpler method using PHP of accessing namespaced XML nodes without declaring a namespace is....
In order to get the value of <su:authorEmail> from the following source
<item>
<title>My important article</title>
<pubDate>Mon, 29 Feb 2017 00:00:00 +0000</pubDate>
<link>https://myxmlsource.com/32984</link>
<guid>https://myxmlsource.com/32984</guid>
<author>Blogs, Jo</author>
<su:departments>
<su:department>Human Affairs</su:department>
</su:departments>
<su:authorHash>4f329b923419b3cb2c654d615e22588c</su:authorHash>
<su:authorEmail>hIwW14tLc+4l/oo7agmRrcjwe531u+mO/3IG3xe5jMg=</su:authorEmail>
<dc:identifier>/32984/Download/0032984-11042.docx</dc:identifier>
<dc:format>Journal article</dc:format>
<dc:creator>Blogs, Jo</dc:creator>
<slash:comments>0</slash:comments>
</item>
Use the following code:
$rss = new DOMDocument();
$rss->load('https://myxmlsource.com/rss/xml');
$nodes = $rss->getElementsByTagName('item');
foreach ($nodes as $node) {
$title = $node->getElementsByTagName('title')->item(0)->nodeValue;
$author = $node->getElementsByTagName('author')->item(0)->nodeValue;
$authorHash = $node->getElementsByTagName('authorHash')->item(0)->nodeValue;
$department = $node->getElementsByTagName('department')->item(0)->nodeValue;
$email = decryptEmail($node->getElementsByTagName('authorEmail')->item(0)->nodeValue);
}

PHP - String could not be parsed as XML [duplicate]

This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 8 years ago.
I am currently using the following code, but no result is returned:
<?php
$url = 'http://myknowledge.org.uk/xml';
$xml = new SimpleXMLElement(file_get_contents($url));
foreach ($xml->item as $item) {
$title = $item->title;
}
echo $title;
?>
The XML Code:
<?xml version="1.0" encoding="utf-8"?>
<item>
<title>Apple</title>
<notableFor>Fruit</notableFor>
<wikiid>Apple</wikiid>
<description>The apple is the pomaceous fruit of the apple tree, Malus domestica of the rose family. It is one of the most widely cultivated tree fruits, and the most widely known of the many members of genus Malus that are used by humans.</description>
<img></img>
<website></website>
<translate>
<de>Äpfel</de>
<fr>pomme</fr>
<it>mela</it>
<es>manzana</es>
<ru>яблоко</ru>
</translate>
<nutritionalInfomation name="Apple" quantity="100g">
<calories>52</calories>
<carb>14</carb>
<fibre>2.4</fibre>
<protein>0.3</protein>
<fat>0.2</fat>
</nutritionalInfomation>
</item>
If anybody has an idea how to fix this I would love to know. Thanks.
The XML appears to be invalid in lines 4 and 5:
<notableFor>Fruit</title>
<wikiid>Apple</title>
Which should be:
<notableFor>Fruit</notableFor>
<wikiid>Apple</wikiid>
I recommend using the XML validator at http://www.w3schools.com/xml/xml_validator.asp to debug errors with your XML code.
Also, as your root element is item, you may want to change your PHP code:
<?php
$url = 'http://myknowledge.org.uk/xml';
$item = new SimpleXMLElement(file_get_contents($url));
$title = $item->title;
$description = $item->description;
?>
(I don't have a copy of PHP on hand to test this, but according to http://php.net/manual/en/simplexml.examples-basic.php, this should work)
Xml can have only 1 root element, in your example the root is item
When loading to SimpleXML you can get the root name with $xml->getName()
$url = 'http://myknowledge.org.uk/xml';
$item = new SimpleXMLElement($url, null, true);
$title = $item->title;
$description = $item->description;
Or you should enclose you items in another root i.e items if you need multiple

To get xml node value using php

I want to get the value present in xml node for that I written following code.
The code aim is to get
1.Board value,
2.Address->City value,
3.Photo->PropertyPhoto->SequenceId value.
Code is:
//some code
$fsp = $xml->saveXML();
echo $fsp; //it's output is given below
$s = simplexml_import_dom($fsp);
echo $s->PropertyDetails[0]->Board;
echo $s->PropertyDetails[0]->Address->City;
echo $s->PropertyDetails[0]->Photo->PropertyPhoto->SequenceId;
OUTPUT OF echo $fsp is:
<?xml version="1.0" encoding="UTF-8"?>
<PropertyDetails ID="13953882" LastUpdated="Thu, 09 Jan 2014 01:43:48 GMT">
<ListingID>188691</ListingID>
<Board>117</Board>
<Address>
<StreetAddress>B LOCAL RD</StreetAddress>
<AddressLine1>B LOCAL RD</AddressLine1>
<City>PORT REXTON</City>
<Province>Newfoundland & Labrador</Province>
<PostalCode>A0C2H0</PostalCode>
<Country>Canada</Country>
</Address>
<Photo>
<PropertyPhoto>
<SequenceId>1</SequenceId>
</PropertyPhoto>
<PropertyPhoto>
<SequenceId>12</SequenceId>
</PropertyPhoto>
</Photo>
<ViewType>Ocean view</ViewType>
It doesn't given any output.
Output required is:
117
PORT REXTON
1,12
Help me.
A couple things I see here. First of all, your XML is not properly formatted. Your PropertyDetails tag is not closed. So close that out, and instead of using a DOMDocument, use the SimpleXMLElement class.
First your XML needs to corrected like thus:
<?xml version="1.0" encoding="UTF-8"?>
<PropertyDetails ID="13953882" LastUpdated="Thu, 09 Jan 2014 01:43:48 GMT">
<ListingID>188691</ListingID>
<Board>117</Board>
<Address>
<StreetAddress>B LOCAL RD</StreetAddress>
<AddressLine1>B LOCAL RD</AddressLine1>
<City>PORT REXTON</City>
<Province>Newfoundland & Labrador</Province>
<PostalCode>A0C2H0</PostalCode>
<Country>Canada</Country>
</Address>
<Photo>
<PropertyPhoto>
<SequenceId>1</SequenceId>
</PropertyPhoto>
<PropertyPhoto>
<SequenceId>12</SequenceId>
</PropertyPhoto>
</Photo>
<ViewType>Ocean view</ViewType>
</PropertyDetails>
Notice the last line.
Now use SimpleXMLElement and you will be close to accessing the way you want.
$s = new SimpleXMLElement($fsp);
echo $s->Board;
echo $s->Address->City;
$sequence_ids = array();
foreach($s->Photo->PropertyPhoto as $PropertyPhoto)
$sequence_ids[] = $PropertyPhoto->SequenceId;
echo implode(',',$sequence_ids);
Since is your root node in the XML, you dont need to access it via ->PropertyDetails[0]. It knows.
Hope this helps.
First load the xml from the string within your var:
$doc = new DOMDocument();
$doc->load($fsp);
apidoc here: http://www.php.net/manual/en/domdocument.loadxml.php
And then read the tags requested:
//board
$boards = $doc->getElementsByTagName('Board');
echo $boards[0]->nodeValue, PHP_EOL;
//city
$cities = $doc->getElementsByTagName('City');
echo $cities[0]->nodeValue, PHP_EOL;
//sequence ids
$arrIds = array();
foreach ($doc->getElementsByTagName('SequenceId') as $sid) $arrIds[] = $sid->nodeValue;
echo implode(',', $arrIds);
This assumes you only have only one listing within your file! Otherwise you have to do the tag-lookups depending on parent-nodes (not on global document).
Hope this helps!

Parse XML namespaces with php SimpleXML

I know this has been asked many many times but I haven't been able to get any of the suggestions to work with my situation and I have searched the web and here and tried everything and anything and nothing works. I just need to parse this XML with the namespace cap: and just need four entries from it.
<?xml version="1.0" encoding="UTF-8"?>
<entry>
<id>http://alerts.weather.gov/cap/wwacapget.php?x=TX124EFFB832F0.SpecialWeatherStatement.124EFFB84164TX.LUBSPSLUB.ac20a1425c958f66dc159baea2f9e672</id>
<updated>2013-05-06T20:08:00-05:00</updated>
<published>2013-05-06T20:08:00-05:00</published>
<author>
<name>w-nws.webmaster#noaa.gov</name>
</author>
<title>Special Weather Statement issued May 06 at 8:08PM CDT by NWS</title>
<link href="http://alerts.weather.gov/cap/wwacapget.php?x=TX124EFFB832F0.SpecialWeatherStatement.124EFFB84164TX.LUBSPSLUB.ac20a1425c958f66dc159baea2f9e672"/>
<summary>...SIGNIFICANT WEATHER ADVISORY FOR COCHRAN AND BAILEY COUNTIES... AT 808 PM CDT...NATIONAL WEATHER SERVICE DOPPLER RADAR INDICATED A STRONG THUNDERSTORM 30 MILES NORTHWEST OF MORTON...MOVING SOUTHEAST AT 25 MPH. NICKEL SIZE HAIL...WINDS SPEEDS UP TO 40 MPH...CONTINUOUS CLOUD TO GROUND LIGHTNING...AND BRIEF MODERATE DOWNPOURS ARE POSSIBLE WITH</summary>
<cap:event>Special Weather Statement</cap:event>
<cap:effective>2013-05-06T20:08:00-05:00</cap:effective>
<cap:expires>2013-05-06T20:45:00-05:00</cap:expires>
<cap:status>Actual</cap:status>
<cap:msgType>Alert</cap:msgType>
<cap:category>Met</cap:category>
<cap:urgency>Expected</cap:urgency>
<cap:severity>Minor</cap:severity>
<cap:certainty>Observed</cap:certainty>
<cap:areaDesc>Bailey; Cochran</cap:areaDesc>
<cap:polygon>34.19,-103.04 34.19,-103.03 33.98,-102.61 33.71,-102.61 33.63,-102.75 33.64,-103.05 34.19,-103.04</cap:polygon>
<cap:geocode>
<valueName>FIPS6</valueName>
<value>048017 048079</value>
<valueName>UGC</valueName>
<value>TXZ027 TXZ033</value>
</cap:geocode>
<cap:parameter>
<valueName>VTEC</valueName>
<value>
</value>
</cap:parameter>
</entry>
I am using simpleXML and I have a small simple test script set up and it works great for parsing regular elements. I can't for the dickens of me find or get a way to parse the elements with the namespaces.
Here is a small sample test script with code I am using and works great for parsing simple elements. How do I use this to parse namespaces? Everything I've tried doesn't work. I need it to be able to create variables so I can be able to embed them in HTML for style.
<?php
$html = "";
// Get the XML Feed
$data = "http://alerts.weather.gov/cap/tx.php?x=1";
// load the xml into the object
$xml = simplexml_load_file($data);
for ($i = 0; $i < 10; $i++){
$title = $xml->entry[$i]->title;
$summary = $xml->entry[$i]->summary;
$html .= "<p><strong>$title</strong></p><p>$summary</p><hr/>";
}
echo $html;
?>
This works fine for parsing regular elements but what about the ones with the cap: namespace under the entry parent?
<?php
ini_set('display_errors','1');
$html = "";
$data = "http://alerts.weather.gov/cap/tx.php?x=1";
$entries = simplexml_load_file($data);
if(count($entries)):
//Registering NameSpace
$entries->registerXPathNamespace('prefix', 'http://www.w3.org/2005/Atom');
$result = $entries->xpath("//prefix:entry");
//echo count($asin);
//echo "<pre>";print_r($asin);
foreach ($result as $entry):
$title = $entry->title;
$summary = $entry->summary;
$html .= "<p><strong>$title</strong></p><p>$summary</p>$event<hr/>";
endforeach;
endif;
echo $html;
?>
Any help would be greatly appreciated.
-Thanks
I have given same type of answer here - solution to your question
You just need to register Namespace and then you can work normally with simplexml_load_file and XPath
<?php
$data = "http://alerts.weather.gov/cap/tx.php?x=1";
$entries = file_get_contents($data);
$entries = new SimpleXmlElement($entries);
if(count($entries)):
//echo "<pre>";print_r($entries);die;
//alternate way other than registring NameSpace
//$asin = $asins->xpath("//*[local-name() = 'ASIN']");
$entries->registerXPathNamespace('prefix', 'http://www.w3.org/2005/Atom');
$result = $entries->xpath("//prefix:entry");
//echo count($asin);
//echo "<pre>";print_r($result);die;
foreach ($result as $entry):
//echo "<pre>";print_r($entry);die;
$dc = $entry->children('urn:oasis:names:tc:emergency:cap:1.1');
echo $dc->event."<br/>";
echo $dc->effective."<br/>";
echo "<hr>";
endforeach;
endif;
That's it.
Here's an alternative solution:
<?php
$xml = <<<XML
<?xml version = '1.0' encoding = 'UTF-8' standalone = 'yes'?>
<?xml-stylesheet href='http://alerts.weather.gov/cap/capatom.xsl' type='text/xsl'?>
<!--
This atom/xml feed is an index to active advisories, watches and warnings
issued by the National Weather Service. This index file is not the complete
Common Alerting Protocol (CAP) alert message. To obtain the complete CAP
alert, please follow the links for each entry in this index. Also note the
CAP message uses a style sheet to convey the information in a human readable
format. Please view the source of the CAP message to see the complete data
set. Not all information in the CAP message is contained in this index of
active alerts.
-->
<feed
xmlns = 'http://www.w3.org/2005/Atom'
xmlns:cap = 'urn:oasis:names:tc:emergency:cap:1.1'
xmlns:ha = 'http://www.alerting.net/namespace/index_1.0'
>
<!-- http-date = Tue, 07 May 2013 04:14:00 GMT -->
<id>http://alerts.weather.gov/cap/tx.atom</id>
<logo>http://alerts.weather.gov/images/xml_logo.gif</logo>
<generator>NWS CAP Server</generator>
<updated>2013-05-06T23:14:00-05:00</updated>
<author>
<name>w-nws.webmaster#noaa.gov</name>
</author>
<title>Current Watches, Warnings and Advisories for Texas Issued by the National Weather Service</title>
<link href='http://alerts.weather.gov/cap/tx.atom'/>
<entry>
<id>http://alerts.weather.gov/cap/wwacapget.php?x=TX124EFFB8AA78.FireWeatherWatch.124EFFD70270TX.EPZRFWEPZ.1716207877d94d15d43d410892b9f175</id>
<updated>2013-05-06T23:14:00-05:00</updated>
<published>2013-05-06T23:14:00-05:00</published>
<author>
<name>w-nws.webmaster#noaa.gov</name>
</author>
<title>Fire Weather Watch issued May 06 at 11:14PM CDT until May 08 at 10:00PM CDT by NWS</title>
<link href="http://alerts.weather.gov/cap/wwacapget.php?x=TX124EFFB8AA78.FireWeatherWatch.124EFFD70270TX.EPZRFWEPZ.1716207877d94d15d43d410892b9f175"/>
<summary>...CRITICAL FIRE CONDITIONS EXPECTED WEDNESDAY ACROSS FAR WEST TEXAS AND THE SOUTHWEST NEW MEXICO LOWLANDS... .WINDS ALOFT WILL STRENGTHEN OVER THE REGION EARLY THIS WEEK...AHEAD OF AN UPPER LEVEL TROUGH FORECAST TO MOVE THROUGH NEW MEXICO AND TEXAS ON WEDNESDAY. SURFACE LOW PRESSURE WILL ALSO DEVELOP TO OUR EAST AS THE TROUGH APPROACHES. THIS COMBINATION WILL RESULT</summary>
<cap:event>Fire Weather Watch</cap:event>
<cap:effective>2013-05-06T23:14:00-05:00</cap:effective>
<cap:expires>2013-05-08T22:00:00-05:00</cap:expires>
<cap:status>Actual</cap:status>
<cap:msgType>Alert</cap:msgType>
<cap:category>Met</cap:category>
<cap:urgency>Future</cap:urgency>
<cap:severity>Moderate</cap:severity>
<cap:certainty>Possible</cap:certainty>
<cap:areaDesc>El Paso; Hudspeth</cap:areaDesc>
<cap:polygon></cap:polygon>
<cap:geocode>
<valueName>FIPS6</valueName>
<value>048141 048229</value>
<valueName>UGC</valueName>
<value>TXZ055 TXZ056</value>
</cap:geocode>
<cap:parameter>
<valueName>VTEC</valueName>
<value>/O.NEW.KEPZ.FW.A.0018.130508T1900Z-130509T0300Z/</value>
</cap:parameter>
</entry>
<entry>
<id>http://alerts.weather.gov/cap/wwacapget.php?x=TX124EFFABB2F0.AirQualityAlert.124EFFC750DCTX.HGXAQAHGX.7f2cf548a67d403f0541492b2804d621</id>
<updated>2013-05-06T14:16:00-05:00</updated>
<published>2013-05-06T14:16:00-05:00</published>
<author>
<name>w-nws.webmaster#noaa.gov</name>
</author>
<title>Air Quality Alert issued May 06 at 2:16PM CDT by NWS</title>
<link href="http://alerts.weather.gov/cap/wwacapget.php?x=TX124EFFABB2F0.AirQualityAlert.124EFFC750DCTX.HGXAQAHGX.7f2cf548a67d403f0541492b2804d621"/>
<summary>...OZONE ACTION DAY FOR TUESDAY... THE TEXAS COMMISSION ON ENVIRONMENTAL QUALITY (TCEQ)...HAS ISSUED AN OZONE ACTION DAY FOR THE HOUSTON...GALVESTON...AND BRAZORIA AREAS FOR TUESDAY...MAY 7 2013. ATMOSPHERIC CONDITIONS ARE EXPECTED TO BE FAVORABLE FOR PRODUCING HIGH LEVELS OF OZONE POLLUTION IN THE HOUSTON...GALVESTON AND</summary>
<cap:event>Air Quality Alert</cap:event>
<cap:effective>2013-05-06T14:16:00-05:00</cap:effective>
<cap:expires>2013-05-07T19:15:00-05:00</cap:expires>
<cap:status>Actual</cap:status>
<cap:msgType>Alert</cap:msgType>
<cap:category>Met</cap:category>
<cap:urgency>Unknown</cap:urgency>
<cap:severity>Unknown</cap:severity>
<cap:certainty>Unknown</cap:certainty>
<cap:areaDesc>Brazoria; Galveston; Harris</cap:areaDesc>
<cap:polygon></cap:polygon>
<cap:geocode>
<valueName>FIPS6</valueName>
<value>048039 048167 048201</value>
<valueName>UGC</valueName>
<value>TXZ213 TXZ237 TXZ238</value>
</cap:geocode>
<cap:parameter>
<valueName>VTEC</valueName>
<value></value>
</cap:parameter>
</entry>
</feed>
XML;
$sxe = new SimpleXMLElement($xml);
$capFields = $sxe->entry->children('cap', true);
echo "Event: " . (string) $capFields->event . "\n";
echo "Effective: " . (string) $capFields->effective . "\n";
echo "Expires: " . (string) $capFields->expires . "\n";
echo "Severity: " . (string) $capFields->severity . "\n";
Output:
Event: Fire Weather Watch
Effective: 2013-05-06T23:14:00-05:00
Expires: 2013-05-08T22:00:00-05:00
Severity: Moderate

Parsing WordPress XML, slash:comments syntax?

This is really just a syntax question.
I have a PHP script that parses my WordPress feed and returns the latest posts. I also want my script to parse the # of comments, but the WordPress feed XML object for number of comments has a colon in it (slash:comments). It causes the following error:
Parse error: syntax error, unexpected
':' in ... on line ...
I have tried each of the following without luck:
$xml->slash:comments
$comments = 'slash:comments'
$xml->$comments
$xml->slash.':'.comments
$xml->{slash:comments}
$xml->{'slash:comments'}
How do I parse an object with a colon?
Alternatively, you can use xpath() to access the nodes. Given the following as an xml string:
<entry>
<id>http://gdata.youtube.com/feeds/api/videos/xyz12345678</id>
<published>2007-01-17T23:41:00.000Z</published>
<updated>2010-11-14T03:52:25.000Z</updated>
<yt:location>Mount Washington Observatory, NH</yt:location>
<media:group>
<media:title type='plain'>Example of a Title</media:title>
<media:duration seconds='126'/>
</media:group>
</entry>
You could do this:
$xml = simplexml_load_string(*xmlstring_from_above*);
$location = $xml->xpath('yt:location');
echo($location[0]); // output: "Mount Washington Observatory, NH"
$title = $xml->xpath('media:group/media:title');
echo($title[0]); // output: "Example of a Title"
$duration = $xml->xpath('media:group/media:duration');
echo($duration[0]['seconds']); // output: "126"
As you can see, to get the nodes with colons, you may use xpath() with a relative path to the node.
A variable in PHP can never have a colon in it. Therefore, you should check your XML parser to see how it handles colons.
$string = file_get_contents("http://domain.tld/?feed=rss2");
$string = str_replace('slash:comments','slashcomments',$string);
$xml = simplexml_load_string($string);
Use str_replace to remove the colons from the string and allow simplexml_load_string to function as normal.
For example:
$string = file_get_contents("http://domain.tld/?feed=rss2");
$string = str_replace('slash:comments','slashcomments',$string);
$xml = simplexml_load_string($string);
foreach ($xml->channel->item as $val) {
echo $val->pubDate.'<br />';
echo $val->title.'<br />';
echo $val->slashcomments.'<br /><br />';
}
... should return the published date, title, and number of comments of the posts listed in a WordPress feed. My code is more advanced, but this illustrates the workaround.
Thank you, Arda Xi, for your help!

Categories