getting xml from URL into variable - php

I am trying to get an xml feed from a url
http://api.eve-central.com/api/marketstat?typeid=1230&regionlimit=10000002
but seem to be failing miserably. I have tried
new SimpleXMLElement,
file_get_contents and
http_get
Yet none of these seem to echo a nice XML feed when I either echo or print_r. The end goal is to eventually parse this data but getting it into a variable would sure be a nice start.
I have attached my code below. This is contained within a loop and $typeID does in fact give the correct ID as seen above
$url = 'http://api.eve-central.com/api/marketstat?typeid='.$typeID.'&regionlimit=10000002';
echo $url."<br />";
$xml = new SimpleXMLElement($url);
print_r($xml);
I should state that the other strange thing I am seeing is that when I echo $url, i get
http://api.eve-central.com/api/marketstat?typeid=1230®ionlimit=10000002
the &reg is the registered trademark symbol. I am unsure if this is "feature" in my browser, or a "feature" in my code

Try the following:
<?php
$typeID = 1230;
// set feed URL
$url = 'http://api.eve-central.com/api/marketstat?typeid='.$typeID.'&regionlimit=10000002';
echo $url."<br />";
// read feed into SimpleXML object
$sxml = simplexml_load_file($url);
// then you can do
var_dump($sxml);
// And now you'll be able to call `$sxml->marketstat->type->buy->volume` as well as other properties.
echo $sxml->marketstat->type->buy->volume;
// And if you want to fetch multiple IDs:
foreach($sxml->marketstat->type as $type){
echo $type->buy->volume . "<br>";
}
?>

You need to fetch the data from the URL in order to make an XML object.
$url = 'http://api.eve-central.com/api/marketstat?typeid='.$typeID.'&regionlimit=10000002';
$xml = new SimpleXMLElement(file_get_contents($url));
// pre tags to format nicely
echo '<pre>';
print_r($xml);
echo '</pre>';

Related

PHP, XML element path

Hey I am trying to get viewers from XML file. Problem is in path cuz other paths were working for me. I guess problem is because it's element? <media:statistics views="131"/>
$url = "https://www.youtube.com/feeds/videos.xml?channel_id=UCH7Hj6l_xDmbyvjQOA5Du0g";
$xml = simplexml_load_file($url);
$views = $xml->entry[0]->children('media', true)->group[0]->children('media', true)->community[0]->children('media', true)->attributes('statistics');
echo $views;
You could get the views by using instead of using ->attributes('statistics') use the statistics property first, and from that, get the views from the attributes:
->statistics->attributes()->views;
The code could look like:
$url = "https://www.youtube.com/feeds/videos.xml?channel_id=UCH7Hj6l_xDmbyvjQOA5Du0g";
$xml = simplexml_load_file($url);
$views = $xml->entry[0]->children('media', true)->group[0]->children('media', true)->community[0]->children('media', true)->statistics->attributes()->views;
echo $views;
Output
131

Laravel: Parsing XML with SimpleXML namespace issue [duplicate]

This question has two parts.
Part 1. Yesterday I had some code which would echo the entire content of the XML from an RSS feed. Then I deleted it from my php document, saved over it, and I am totally kicking myself.
I believe the syntax went something like this:
$xml = simplexml_load_file($url);
echo $xml;
I tried that again and it is not working, so apparently I forgot the correct syntax and could use your help, dear stackoverflow question answerers.
I keep trying to figure out what I was doing and I am unable to find an example on Google or the PHP site. I tried the print_r($url); command, and it gives me what appears to be an atomized version of the feed. I want the whole string, warts and all. I realize that I could just type the RSS link into the window and see it, but it was helpful to have it on my PHP page as I am coding and noding.
Part 2 The main reason I wanted to reconstruct this is because I am trying to parse nodes off a blog RSS in order to display it on a webpage hosted on a private domain. I posted a dummy blog and discovered an awkward formatting glitch when I failed to add a title to one of the dummy posts.
So what does one do in this situation? I tried a little:
if(entry->title == "")
{$entryTitle = "untitled";}
That did not work at all.
Here's my entire php script for the handling of the blog:
<?php
/*create variables*/
$subtitle ="";
$entryTitle="";
$html = "";
$pubDate ="";
/*Store RSS feed address in new variable*/
$url = "http://www.blogger.com/feeds/6552111825067891333/posts/default";
/*Retrieve BLOG XML and store it in PHP object*/
$xml = simplexml_load_file($url);
print_r($xml);
/*Parse blog subtitle into HTML and echo it on the page*/
$subtitle .= "<h2 class='blog'>" . $xml->subtitle . "</h2><br />";
echo $subtitle;
/*Go through all the entries and parse them into HTML*/
foreach($xml->entry as $entry){
/*retrieve publication date*/
$xmlDate = $entry->published;
/*Convert XML timestamp into PHP timestamp*/
$phpDate = new DateTime(substr($xmlDate,0,19));
/*Format PHP timestamp to something humans understand*/
$pubDate .= $phpDate->format('l\, F j\, Y h:i A');
if ($entry->title == "")
{
$entryTitle .= "Untitled";
}
echo $entry->title;
/*Pick through each entry and parse each XML tree node into an HTML ready blog post*/
$html .= "<h3 class='blog'>".$entry->title . "<span class='pubDate'> | " .$pubDate . "</span></h3><p class='blog'>" . $entry->content . "</p>";
/*Print the HTML to the web page*/
echo $html;
/*Set the variables back to empty strings so they do not repeat data upon reiteration*/
$html = "";
$pubDate = "";
}
?>
According to the php manual:
$xml = new SimpleXMLElement($string);
.
.
.
then if you want to echo the result:
echo $xml->asXML();
or save the xml to a file:
$xml->asXML('blog.xml');
References
http://php.net/manual/fr/simplexmlelement.asxml.php
http://spotlesswebdesign.com/blog.php?id=14
Part 1
This is still not exactly what I wanted, but rather a very tidy and organized way of echoing the xml data:
$url = "http://www.blogger.com/feeds/6552111825067891333/posts/default";
$xml = simplexml_load_file($url);
echo '<pre>';
print_r($xml);
Part 2
I had to get firephp running so I could see exactly what elements php was encountering when it reached an entry without a blog title. Ultimately it is an empty array. Therefore, the simple:
if(empty($entry->title))
works perfectly. For string comparison, I found that you can simply cast it as a string. For my purposes, that was unnecessary.
The simplexml_load_file returns an SimpleXMLElement, so:
print_r($xml);
will show its minor objects and arrays.
After your tweaks you can call $xml->asXML("filename.xml"); as #Tim Withers pointed out.
Part 1: echo $xml->asXML(); - http://www.php.net/manual/en/simplexmlelement.asxml.php
Part 2: php SimpleXML check if a child exists
$html .= "<h3 class='blog'>".($entry->title!=null?$entry->title:'No Title')
. "<span class='pubDate'> | " .$pubDate . "</span></h3><p class='blog'>"
. $entry->content . "</p>";
Note I would probably load the url like this:
$feedUrl = 'http://www.blogger.com/feeds/6552111825067891333/posts/default';
$rawFeed = file_get_contents($feedUrl);
$xml = new SimpleXmlElement($rawFeed);
Based on your comment in regards to part 1, I am not sure if the XML is being loaded completely. If you try loading it this way, it should display all the XML data.

PHP, Convert iTunes RSS to JSON

I am trying to utilize simplexml to convert an iTunes RSS Feed to JSON so I can better parse it. The issue I am having is that it is not coming back as correctly formatted JSON.
$feed_url = 'https://podcasts.subsplash.com/c2yjpyh/podcast.rss';
$feed_contents = file_get_contents($feed_url);
$xml = simplexml_load_string($feed_contents);
$podcasts = json_decode(json_encode($xml));
print_r($podcasts);
Is there a better way to be attempting this to get the correct result?
Thanks to IMSoP for pointing me in the right direction! This took a bit of studying but the solution ends up being very simple! Instead of trying to convert to a JSON format, just use SimpleXML. However, due to the namespaces, it does require an additional line to map the itunes: prefix.
So in my iTunes feed rss, the following line exists: xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd So we just reference this to make accessing the values very easy. Here is a quick example:
$rss = simplexml_load_file('https://podcasts.example.com/podcast.rss');
foreach ($rss->channel->item as $item){
// Now we define the map for the itunes: namespace
$itunes = $item->children('http://www.itunes.com/dtds/podcast-1.0.dtd');
// This is a value WITHOUT the itunes: namespace
$title = $item->title;
// This is a value WITH the itunes: namespace
$author = $itunes->author;
echo $title . '<br>';
echo $author . '<br>';
}
The other little issue that I ran into is getting attributes such as the url for images and audio links. That is accomplished by using the attributes() function like so:
// Access attributes WITH itunes: namespace
$image = $itunes->image->attributes();
// Access attributes WITHOUT itunes: namespace
$audio = $item->enclosure->attributes();
// To echo these we simple add the desired attribute in `[]`:
echo $image['href'] . '<br>';
echo $audio['url'] . '<br>';

Simplexml_load_file empty array

I try to load this document:
$url = "http://en.wikipedia.org/w/api.php?action=query&titles=Electrophoresis&prop=langlinks&lllimit=500";
When I run it in browser, everything is fine.
When I do this:
ini_set('user_agent', 'XX123456789 (localhost; myemailaddress)'); //sets info for authentication
$content = file_get_content($url);
var_dump($content);
It return the same xml document as my browser show.
However when I try to
$content_arrays = Simplexml_load_file($content);
echo '<pre>', print_r($content_arrays), '</pre>';
It return a bunch of empty arrays. I just dont get why.
simplexml_load_file returns an object, not an array. So you can't just print it with print_r. You need to do more work to navigate through the SimpleXMLElement.

PHP simplexml_load_file with special chars in URL

I'm attempting to retrieve a local weather forecast, based on the IP of the user.
I'm using geoplugin.net to get the user location and feed the city and country name to the Google Weather API.
//Get user IP
$ip = $_SERVER['REMOTE_ADDR'];
$geolocation = unserialize(file_get_contents('http://www.geoplugin.net/php.gp?ip='.$ip));
$geo_city = $geolocation['geoplugin_city'];
$geo_country = $geolocation['geoplugin_countryName'];
$file = "http://www.google.com/ig/api?weather=".$geo_city.",".$geo_country;
$xml = simplexml_load_file($file);
//Echo content of retrieved XML for debugging purposes
echo "<pre>";
print_r($xml);
echo "</pre>";
It works well for most cases, but when I try it on my own IP, I get Søborg, Denmark (which is not 100% accurate, but close enough) and that gives me an almost empty response from the weather API.
The main suspect in the case, is the dastardly "ø"-character.
The XML that I want can be seen here: http://www.google.com/ig/api?weather=S%C3%B8borg,Denmark
The XML that I'm getting can be seen here: http://www.google.com/ig/api?weather=S
When I type this URL into the browser it works fine:
http://www.google.com/ig/api?weather=Søborg,Denmark
When I use this version it works as well (in the browser):
http://www.google.com/ig/api?weather=S%C3%B8borg,Denmark
but this version returns the forecast for Borg,Syddanmark:
http://www.google.com/ig/api?weather=S%26oslash%3Bborg,Denmark
None of the above returns the desired result, when fed to the simplexml_load_file().
As stated, I suspect that it is a character set issue, but I can't figure out what to do about it.
What is the correct way to solve it?
I know that I can use latitude and longtitude as parameters for Google Weather API instead, but that's just circumventing the problem, not solving it.
If you URL-decode S%26oslash%3Bborg you'll see that this string corresponds to Søborg which gives us Søborg after we decode HTML entities like so:
$city = 'S%26oslash%3Bborg,Denmark';
echo $city = rawurldecode($city);
//prints Søborg,Denmark
echo $city = html_entity_decode($city, 0, 'UTF-8');
//prints Søborg,Denmark
echo $city = rawurlencode($city);
//prints S%C3%B8borg%2CDenmark
And then:
$xml = file_get_contents('http://www.google.com/ig/api?weather='.$city);
$xml = mb_convert_encoding($xml, 'UTF-8');
$xml = simplexml_load_string($xml);
echo $xml->weather->forecast_information->city['data'];
Outputs expected:
Søborg, Capital Region of Denmark
It does indeed sound like a character set issue. Have you tried converting the URL to another encoding, e.g. using iconv, before passing the result into simplexml_load_file()?
Try this out:
$file = "http://www.google.com/ig/api?weather=" . $geo_city . "," . $geo_country;
$data = file_get_contents($file);
$data = mb_convert_encoding($data, "UTF-8", "ISO-8859-2");
$xml = simplexml_load_string($data);
echo "<pre>"; print_r($xml); echo "</pre>";
It's taken from this maybe similar thread: https://stackoverflow.com/a/5136549/949476

Categories