I cannot seem to parse out the metrics for an organic keyword. I am using simplexml_load_string to load the whole response string and then when I print_r the object I can see this:
[0] => SimpleXMLElement Object
(
[id] => http://www.google.com/analytics/feeds/data?ids=ga:480&ga:keyword=cats&start-date=2011-04-10&end-date=2011-07-24
[updated] => 2011-07-23T17:00:00.001-07:00
[title] => ga:keyword=cats
[link] => SimpleXMLElement Object
(
[@attributes] => Array
(
[rel] => alternate
[type] => text/html
[href] => http://www.google.com/analytics
)
)
)
But when I look at the actual (pre-formatted) response I see some extra data that didn’t survive the format:
<entry gd:etag="W/"hdSFEs."" gd:kind="analytics#datarow">
<id>http://www.google.com/analytics/feeds/data?ids=ga:430&ga:keyword=cats&start-date=2011-04-10&end-date=2011-07-24</id>
<updated>2011-07-23T17:00:00.001-07:00</updated>
<title>ga:keyword=cats</title>
<link rel="alternate" type="text/html" href="http://www.google.com/analytics"/>
<dxp:dimension name="ga:keyword" value="cats"/>
<dxp:metric confidenceInterval="0.0" name="ga:organicSearches" type="integer" value="2"/>
</entry>
I need that metric value at the bottom, in this case it’s two. How can I get it?
Thanks!
Edit: the easy way out is this:
var_dump($object->xpath('dxp:metric'));The problem is that simplexml has a ‘gotcha’ with namespaces. As kudo’s to squirrel, you indeed need to use namespaces, but I have a hunch that you only posted a part of the xml response and not the whole response.
There is an excellent post about it here: http://blogs.sitepoint.com/simplexml-and-namespaces/
In order to fetch the value of the metric (and the metric itself), you can get started with this piece of code.
Be aware that there are some attributes in there that are again in a different namespace.
The rest also has been answered here: Parse XML with Namespace using SimpleXML