How to get data from an phrase in remote XML in php? - php

I wanna get the data from an XML file on remote site from a particular node. But im getting the following error
Warning: simplexml_load_file(): in php line
on the warning 2 : Its loading the File data. Result I wanna is to get the GRate.
Note: I have enabled SimpleXML module on my php installation.
<?php
$url = "http://api.srinivasajewellery.com/getrate/getrate";
$xml = simplexml_load_file($url) or die("not open");
?><pre><?php //print_r($xml); ?></pre><?php
foreach($xml->GRate as $GRate){
printf('$GRate');
}
?>
I have expected to get "3640.00" on my output but error is as follows
Warning: simplexml_load_file(): http://api.srinivasajewellery.com/getrate/getrate:1: parser error : Start tag expected, '<' not found in H:\root\home\srinivasauser-001\www\goldrate\wp-content\themes\twentynineteen\footer.php on line 24
Warning: simplexml_load_file(): {"GRate":"3640.00","SRate":"49.00","PRate":"0.00"} in H:\root\home\srinivasauser-001\www\goldrate\wp-content\themes\twentynineteen\footer.php on line 24
Warning: simplexml_load_file(): ^ in H:\root\home\srinivasauser-001\www\goldrate\wp-content\themes\twentynineteen\footer.php on line 24
not open.

When the URL "http://api.srinivasajewellery.com/getrate/getrate" is requested from PHP with the default settings, it will return the data as JSON. Which might be even easier to parse in this case:
<?php
$url = "http://api.srinivasajewellery.com/getrate/getrate";
$json = json_decode(file_get_contents($url));
echo '$GRate: ' . $json->GRate, "\n";
Output:
$GRate: 3670.00
This can be easily checked by fetching the URL and output it verbatim:
$buffer = file_get_contents($url);
echo $buffer, "\n";
{"GRate":"3670.00","SRate":"50.00","PRate":"0.00"}
As has been demonstrated by Vijay Dohare it is possible to tell that server that XML is preferred. To check if that works, is possible this way, too:
stream_context_get_default(['http' => ['header' => 'Accept: application/xml']]);
$buffer = file_get_contents($url);
echo $buffer, "\n";
The output is not that beautified then (I guess if the data is more, the JSON wouldn't be that easy to read as well as it also would grew larger):
<GetRateController.Rate xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/Savings.Controllers"><GRate>3670.00</GRate><PRate>0.00</PRate><SRate>50.00</SRate></GetRateController.Rate>
This might be similar to when opening the URL in the browser. This is because the browser also sends the Accept request header and it contains XML as well:
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3
Because browser normally accept XML as well (albeit they prefer HTML over it).
So in the end it depends what you prefer. Either the JSON which is less verbose compared to XML (see the very first example code above) or if you want to use XML with SimpleXML:
<?php
$url = "http://api.srinivasajewellery.com/getrate/getrate";
stream_context_get_default(['http' => ['header' => 'Accept: application/xml']]);
$xml = simplexml_load_file($url) or die("not open");
echo '$GRate: ' . $xml->GRate, "\n";
Output:
$GRate: 3670.00

Try following code,
<?php
$url = "http://api.srinivasajewellery.com/getrate/getrate";
$context = stream_context_create(array('http' => array('header' => 'Accept: application/xml')));
$xml = file_get_contents($url, false, $context);
$xml = simplexml_load_string($xml) or die("not open");
foreach($xml->GRate as $GRate){
echo '$GRate: '.$GRate;
}
?>

Related

Cannot read the xml file using simplexml_load_file ();

I am having a problem reading data from an online xml file, when I use the simplexml_load_file () function; I encountered an error.
My code PHP:
$url = "https://www.bidv.com.vn/ServicesBIDV/ExchangeRateServlet";
$xml = simplexml_load_file($url);
echo '<pre>';
print_r($xml);
echo '</pre>';
input eror
Warning: simplexml_load_file(https://www.bidv.com.vn/ServicesBIDV/ExchangeRateServlet): failed to open stream: HTTP request failed! HTTP/1.1 403 Forbidden in D:\All In One\xammp\htdocs\ty_gia_api\index.php on line 12
Warning: simplexml_load_file(): I/O warning : failed to load external entity "https://www.bidv.com.vn/ServicesBIDV/ExchangeRateServlet" in D:\All In One\xammp\htdocs\ty_gia_api\index.php on line 12
Try to get contents from URL like:
$url = "https://www.bidv.com.vn/ServicesBIDV/ExchangeRateServlet";
$xml = simplexml_load_string(shell_exec("curl -k '$url'"));
echo '<pre>';
print_r($xml);
echo '</pre>';
I see the page you try to get is not XML, its JSON.
This will work:
$url = 'https://www.bidv.com.vn/ServicesBIDV/ExchangeRateServlet';
$data = json_decode(shell_exec("curl -k '$url'"), 1);
echo '<pre>';
print_r($data);
echo '</pre>';
var_dump($data);

PHP - simplexml_load_file() - I/O warning : failed to load external entity [duplicate]

I'm trying to create a small application that will simply read an RSS feed and then layout the info on the page.
All the instructions I find make this seem simplistic but for some reason it just isn't working. I have the following
include_once(ABSPATH.WPINC.'/rss.php');
$feed = file_get_contents('http://feeds.bbci.co.uk/sport/0/football/rss.xml?edition=int');
$items = simplexml_load_file($feed);
That's it, it then breaks on the third line with the following error
Error: [2] simplexml_load_file() [function.simplexml-load-file]: I/O warning : failed to load external entity "<?xml version="1.0" encoding="UTF-8"?> <?xm
The rest of the XML file is shown.
I have turned on allow_url_fopen and allow_url_include in my settings but still nothing.
I've tried multiple feeds that all end up with the same result?
I'm going mad here
simplexml_load_file() interprets an XML file (either a file on your disk or a URL) into an object. What you have in $feed is a string.
You have two options:
Use file_get_contents() to get the XML feed as a string, and use e simplexml_load_string():
$feed = file_get_contents('...');
$items = simplexml_load_string($feed);
Load the XML feed directly using simplexml_load_file():
$items = simplexml_load_file('...');
You can also load the content with cURL, if file_get_contents insn't enabled on your server.
Example:
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,"http://feeds.bbci.co.uk/sport/0/football/rss.xml?edition=int");
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
$output = curl_exec($ch);
curl_close($ch);
$items = simplexml_load_string($output);
this also works:
$url = "http://www.some-url";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$xmlresponse = curl_exec($ch);
$xml=simplexml_load_string($xmlresponse);
then I just run a forloop to grab the stuff from the nodes.
like this:`
for($i = 0; $i < 20; $i++) {
$title = $xml->channel->item[$i]->title;
$link = $xml->channel->item[$i]->link;
$desc = $xml->channel->item[$i]->description;
$html .="<div><h3>$title</h3>$link<br />$desc</div><hr>";
}
echo $html;
***note that your node names will differ, obviously..and your HTML might be structured differently...also your loop might be set to higher or lower amount of results.
$url = 'http://legis.senado.leg.br/dadosabertos/materia/tramitando';
$xml = file_get_contents("xml->{$url}");
$xml = simplexml_load_file($url);

Parsing of a XML response

I am completely new to XML.
I have a URL which gives me a XML response. I am facing problems in parsing the response and showing only the details that I want. Currently the url is "https://api.eancdn.com/ean-services/rs/hotel/v3/list?cid=55504&minorRev=99&apiKey=cbrzfta369qwyrm9t5b8y8kf&locale=en_US&currencyCode=USD&xml=%3CHotelListRequest%3E%3Ccity%3ESeattle%3C%2Fcity%3E%3CstateProvinceCode%3EWA%3C%2FstateProvinceCode%3E%3CcountryCode%3EUS%3C%2FcountryCode%3E%3CarrivalDate%3E%3C%2FarrivalDate%3E%3CdepartureDate%3E9%2F1%2F2014%3C%2FdepartureDate%3E%3CRoomGroup%3E%3CRoom%3E%3CnumberOfAdults%3E2%3C%2FnumberOfAdults%3E%3C%2FRoom%3E%3C%2FRoomGroup%3E%3CnumberOfResults%3E25%3C%2FnumberOfResults%3E%3C%2FHotelListRequest%3E"
and I am using the following code:
$feed = file_get_contents($url);
$items = simplexml_load_string($feed);
print_r($items);
and this was the error
file_get_contents( https://api.eancdn.com/ean-services/rs/hotel/v3/list?cid=55504&minorRev=99&apiKey=cbrzfta369qwyrm9t5b8y8kf&locale=en_US&currencyCode=USD&xml=%3CHotelListRequest%3E%3Ccity%3EAmsterdam%3C%2Fcity%3E%3CarrivalDate%3E08/30/2014%3C%2FarrivalDate%3E%3CdepartureDate%3E08/31/2014%3C%2FdepartureDate%3E%3CRoomGroup%3E%3CRoom%3E%3CnumberOfAdults%3E1%3C%2FnumberOfAdults%3E%3C%2FRoom%3E%3C%2FRoomGroup%3E%3CnumberOfResults%3E25%3C%2FnumberOfResults%3E%3C%2FHotelListRequest%3E): failed to open stream: Invalid argument
I have also tried using simplexml_load_file() and it's showing the same error.
file_get_contents on the URL is returning content of type json, that's why simple_xml_load_file cannot parse it. Use this
$feed = file_get_contents("https://api.eancdn.com/ean-services/rs/hotel/v3/list?cid=55504&minorRev=99&apiKey=cbrzfta369qwyrm9t5b8y8kf&locale=en_US&currencyCode=USD&xml=%3CHotelListRequest%3E%3Ccity%3ESeattle%3C%2Fcity%3E%3CstateProvinceCode%3EWA%3C%2FstateProvinceCode%3E%3CcountryCode%3EUS%3C%2FcountryCode%3E%3CarrivalDate%3E%3C%2FarrivalDate%3E%3CdepartureDate%3E9%2F1%2F2014%3C%2FdepartureDate%3E%3CRoomGroup%3E%3CRoom%3E%3CnumberOfAdults%3E2%3C%2FnumberOfAdults%3E%3C%2FRoom%3E%3C%2FRoomGroup%3E%3CnumberOfResults%3E25%3C%2FnumberOfResults%3E%3C%2FHotelListRequest%3E");
//echo $feed;
$json = json_decode($feed);
print_r($json);
Currently when viewed on the browser its an xml but in the script is responds a json.
$url = 'https://api.eancdn.com/ean-services/rs/hotel/v3/list?cid=55504&minorRev=99&apiKey=cbrzfta369qwyrm9t5b8y8kf&locale=en_US&currencyCode=USD&xml=%3CHotelListRequest%3E%3Ccity%3ESeattle%3C%2Fcity%3E%3CstateProvinceCode%3EWA%3C%2FstateProvinceCode%3E%3CcountryCode%3EUS%3C%2FcountryCode%3E%3CarrivalDate%3E%3C%2FarrivalDate%3E%3CdepartureDate%3E9%2F1%2F2014%3C%2FdepartureDate%3E%3CRoomGroup%3E%3CRoom%3E%3CnumberOfAdults%3E2%3C%2FnumberOfAdults%3E%3C%2FRoom%3E%3C%2FRoomGroup%3E%3CnumberOfResults%3E25%3C%2FnumberOfResults%3E%3C%2FHotelListRequest%3E';
$contents = file_get_contents($url);
$data = json_decode($contents, true);
// becomes an array

SimpleXML - I/O warning : failed to load external entity

I'm trying to create a small application that will simply read an RSS feed and then layout the info on the page.
All the instructions I find make this seem simplistic but for some reason it just isn't working. I have the following
include_once(ABSPATH.WPINC.'/rss.php');
$feed = file_get_contents('http://feeds.bbci.co.uk/sport/0/football/rss.xml?edition=int');
$items = simplexml_load_file($feed);
That's it, it then breaks on the third line with the following error
Error: [2] simplexml_load_file() [function.simplexml-load-file]: I/O warning : failed to load external entity "<?xml version="1.0" encoding="UTF-8"?> <?xm
The rest of the XML file is shown.
I have turned on allow_url_fopen and allow_url_include in my settings but still nothing.
I've tried multiple feeds that all end up with the same result?
I'm going mad here
simplexml_load_file() interprets an XML file (either a file on your disk or a URL) into an object. What you have in $feed is a string.
You have two options:
Use file_get_contents() to get the XML feed as a string, and use e simplexml_load_string():
$feed = file_get_contents('...');
$items = simplexml_load_string($feed);
Load the XML feed directly using simplexml_load_file():
$items = simplexml_load_file('...');
You can also load the content with cURL, if file_get_contents insn't enabled on your server.
Example:
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,"http://feeds.bbci.co.uk/sport/0/football/rss.xml?edition=int");
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
$output = curl_exec($ch);
curl_close($ch);
$items = simplexml_load_string($output);
this also works:
$url = "http://www.some-url";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$xmlresponse = curl_exec($ch);
$xml=simplexml_load_string($xmlresponse);
then I just run a forloop to grab the stuff from the nodes.
like this:`
for($i = 0; $i < 20; $i++) {
$title = $xml->channel->item[$i]->title;
$link = $xml->channel->item[$i]->link;
$desc = $xml->channel->item[$i]->description;
$html .="<div><h3>$title</h3>$link<br />$desc</div><hr>";
}
echo $html;
***note that your node names will differ, obviously..and your HTML might be structured differently...also your loop might be set to higher or lower amount of results.
$url = 'http://legis.senado.leg.br/dadosabertos/materia/tramitando';
$xml = file_get_contents("xml->{$url}");
$xml = simplexml_load_file($url);

Twitter feed not working

Hi I use the following PHP code to parse a twitter feed and display the latest two tweets in the footer of a website..
<ul id="twitter_update_list" style="word-wrap:break-word;">
<?php
$doc = new DOMDocument();
$doc->load('http://twitter.com/statuses/user_timeline/fixedgearfrenzy.rss');
$arrFeeds = array();
$count = 0;
foreach ($doc->getElementsByTagName('item') as $node)
{
if($count < 2)
echo('<li><span style="word-wrap:break-word;">'.substr($node->getElementsByTagName('description')->item(0)->nodeValue, 17).' </span>'.substr($node->getElementsByTagName('pubDate')->item(0)->nodeValue, 0, 16).'</li>');
$count = $count + 1;
}
?></ul>
For some reason it seems to not always work and most of the time the following error is displayed..
Warning: DOMDocument::load(http://twitter.com/statuses/user_timeline/fixedgearfrenzy.rss) [domdocument.load]: failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request in /home/fixedge1/public_html/catalog/view/theme/CartMania-Clean/template/common/footer.tpl on line 336Warning: DOMDocument::load() [domdocument.load]: I/O warning : failed to load external entity "http://twitter.com/statuses/user_timeline/fixedgearfrenzy.rss" in /home/fixedge1/public_html/catalog/view/theme/CartMania-Clean/template/common/footer.tpl on line 336
I can't work out why on earth it sometimes works and sometimes doesn't, any ideas??
The website is http://www.fixedgearfrenzy.co.uk and it's the twitter feed in the bottom right
IIRC, Twitter impose a per-hour limit on the number of times you can load a feed. If your results are intermittent, this is probably the reason why. Try caching the feed results locally to avoid re-loading the same data from Twatter over and over again.
You should use a valid user-agent when using DOMDocument to load a remote resource.
<?php
// Set a valid user-agent
$opts = array(
'http' => array(
'user_agent' => 'PHP libxml agent',
)
);
$context = stream_context_create($opts);
libxml_set_streams_context($context);
$doc = new DOMDocument();
$doc->load('http://twitter.com/statuses/user_timeline/fixedgearfrenzy.rss');
$arrFeeds = array();
// rest of your code...

Categories