How to Read Xml data using codeigniter? - php

I want to read xml data using curl in codeigniter. I have create a helper file which will read data from following url: http://www.ekidata.jp/api/l/11302.xml but problem is that i cannot read the data from this url. plz help
Here is my helper file structure:
if (!function_exists('ekidata')) {
function ekidata($type, $code)
{
$apiurl = 'http://www.ekidata.jp/api/'.$type.'/'.$code.'.xml';
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $apiurl);
$response = curl_exec($ch);
curl_close($ch);
$xml = simplexml_load_string($response);
if ($type == 'l') {
return $xml;
} else {
}
}
}
Here is my controller:
function ekidatatest()
{
$this->load->view('ekidatatest');
}
Here is my view:
<?php echo ekidata('l', 11302);?>

I have tested your code and it works ok, the only issue i see is that you are tryin to echo an object (the returned XML variable), try:
print_r (ekidata('l', 11302));
and you should see all the xml object from the file, then you can loop on the object and get the data you need. So if you want the first station name you can get it like this:
$r = ekidata('l', 11302);
echo $r->station[0]->station_name;
and to loop on all stations:
foreach($r->station as $station) {
echo $station->station_name.'<br/>';
}

Related

Retrieving data of curl post in PHP

I am trying to senddata to a url by using curl with codeigniter. I have successfully implemented the code for sending the data as below.
function postToURL($reg_no, $data)
{
$url = 'http://localhost/abcSystem/Web_data/viewPage';
$send_array = array(
'reg_no' =>$reg_no,
'data' =>$data,
);
$fields_string = http_build_query($send_array);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 600);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_REFERER, $url);
$post_data = 'json='.urlencode(json_encode($send_array));
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
$output = curl_exec($ch);
if (curl_errno($ch)) {
die('Couldn\'t send request: ' . curl_error($ch));
} else {
$resultStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($resultStatus == 200) {
print_r('success'); // this is outputting
return $output;
} else {
die('Request failed: HTTP status code: ' . $resultStatus);
}
}
curl_close($ch);
}
The out put is success. I want to see if this post data can be retrieved. So I tried to change the above url controller file as below.
$fp = fopen('php://input', 'r');
$rawData = stream_get_contents($fp);
echo "<pre>";
print_r($rawData);
echo "</pre>";
But nothing is printing. I want to get the data of posting. Please help me on this.
Your Written code
$fp = fopen('php://input', 'r');
$rawData = stream_get_contents($fp);
echo "<pre>";
print_r($rawData);
echo "</pre>";
is not to Print or capture Posted Data . Because you are dealing with Current Page PHP INPUT Streaming , whereas you are posting data on Other URL . So what you need to do is just Put a log of posted data in File. Use below code after $output = curl_exec($ch)
file_put_contents("posted_data.txt", $post_data );
This way you will be able to write your each post in file Posted_data.txt File - Make sure you give proper File Permission. If you want to keep trace of each POST than just make the file name dynamic so per API Call it can write a log.
Another option is to save the $post_data in DATABASE - Which is not suggestable from Security point of view.
Where ever you are calling your postToURL() function, you need to output the result of it.
For example:
$output = postToURL('Example', array());
echo $output;
This is because you are returning the curl output rather outputting it.

How to get xml Curl Response

I am use curl method to get response from server.
but when ehco this response it show as simple data.
but in view source it show xml format.
can anybody tell me how to print response as xml
I am using this code:
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
//curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $post_data_tcetra);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
Use this:
ob_start();
$result = curl_exec($ch);
$xml = ob_get_contents();
ob_end_clean();
echo htmlspecialchars($xml);
The actual function you're searching for is called htmlspecialchars(). It converts symbols like < to to their entity references <.
In my code above, we also need the Output Caching (ob_*) functions, so that we can prevent the output from directly being sent to the browser. I'd suggest you though that you use the better way in the code below:
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
if ($result === false) {
// error handling
}
else {
echo htmlspecialchars($result);
}

Running a for loop on an ASP page

I was trying to download the results of a batch and was coding a program for this.
On an aspx file, I was able to write the following PHP code since the URL included the parameters:
function get_data($url) {
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
for ($i=1; $i<15000; $i++) {
$url = "http://example.com/result.aspx?ClassId=342&TermId=95&StudentId=".$i;
$returned_content = get_data($url);
if (stripos($returned_content,'Roll') !== false) {
echo "Student ID:" . $i;
echo $returned_content;
}
}
However, when a result is queried on a .ASP file, the URL simply says 'results.asp' without any additional parameters. Is there a way to use CURL requests to run a for loop and download this data in a similar manner?
Thanks for any help!

Using the JSON data returned by the last.fm api

I am trying to pull the top 6 artists from last.fm using the last.fm api. I am able to pull in the JSON data and output it just fine. However, when it comes to actually using specific pieces of data, I am at a loss. The only thing that I want to use is the artists' names. Here is the code I have so far.
<?php
$content = get_data('http://ws.audioscrobbler.com/2.0/?method=chart.gettopartists&api_key=xxxxxxxxxxxxxx&format=json&limit=6');
foreach ($content->artist as $artist) {
echo '<li>';
echo "{$artist->name}\n";
echo '</li>';
}
function get_data($url) {
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
?>
The data looks like this:
{"artists":{"artist":[{"name":"Coldplay","playcount":"757749","listeners":"111884","mbid":"cc197bad-dc9c-440d-a5b5-d52ba2e14234","url":"http:\/\/www.last.fm\/music\/Coldplay","streamable":"1","image":[{"#text":"http:\/\/userserve-ak.last.fm\/serve\/34\/210303.jpg","size":"small"},{"#text":"http:\/\/userserve-ak.last.fm\/serve\/64\/210303.jpg","size":"medium"},{"#text":"http:\/\/userserve-ak.last.fm\/serve\/126\/210303.jpg","size":"large"},{"#text":"http:\/\/userserve-ak.last.fm\/serve\/252\/210303.jpg","size":"extralarge"},{"#text":"http:\/\/userserve-ak.last.fm\/serve\/500\/210303\/Coldplay.jpg","size":"mega"}]},{"name":"Rihanna","playcount":"943551","listeners":"102321","mbid":"69989475-2971-49aa-8c53-5d74af88b8be","url":"http:\/\/www.last.fm\/music\/Rihanna","streamable":"1","image":[{"#text":"http:\/\/userserve-ak.last.fm\/serve\/34\/79835799.png","size":"small"},{"#text":"http:\/\/userserve-ak.last.fm\/serve\/64\/79835799.png","size":"medium"},{"#text":"http:\/\/userserve-ak.last.fm\/serve\/126\/79835799.png","size":"large"},{"#text":"http:\/\/userserve-ak.last.fm\/serve\/252\/79835799.png","size":"extralarge"},{"#text":"http:\/\/userserve-ak.last.fm\/serve\/_\/79835799\/Rihanna+PNG.png","size":"mega"}]}}}
Any help would be greatly appreciated!
You need to use json_decode so return json_decode($data);. This will turn the return data in an object that you can traveres. For an associative array use return json_decode($data, true);. See http://php.net/manual/en/function.json-decode.php

XML > PHP only in source code

I have a slight issue whereby the API I'm using for part of my service uses a rsp stat to handle the success / error messages in XML.
So we use a form to post it data and it returns the data like the following example:
<rsp stat="ok">
<success msg="accepted" transactionid="505eeb9c43969d4919c0a6b3f7a4dfbb" messageid="a92eff8d65cf48e9c6e96702a7b07400"/>
</rsp>
The following is most of the script used :
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
// ToDo: Replace the placeholders in brackets with your data.
// For example - curl_setopt($ch, CURLOPT_UsERPWD, 'SMSUser:PassW0rD#');
curl_setopt($ch, CURLOPT_USERPWD, '');
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 100);
$xml = curl_exec($ch);
if (curl_error($ch)) {
print "ERROR ". curl_error($ch) ."\n";
}
curl_close($ch);
print_r($xml);
The only problem is that when it is parsed and displayed via the print_r command , it only displays via source code for some strange reason and we have no idea how to display it via the page
Basically we would like a system whereby if rsp stat="ok" then "Sent" else "unsent".
Well, a simple way could be:
if (strpos($xml, 'stat="ok"') !== false) {
echo "sent";
} else {
echo "unsent";
}
http://codepad.org/pkzsfsMk
This would replace print($xml);.
Put that code in a function, and have the function return your $xml.
Assuming you had a function called getRspStat() you could just do like:
echo getRspStat();
If you do something like that:
(see also on CodePad.org)
function xmlRequestWasSuccessful($xml) {
$result = simplexml_load_string($xml);
$result = (string)$result['stat'];
if ($result == 'ok') {
return true;
} else {
return false;
}
}
$xml = '<rsp stat="ok">
<success msg="accepted" transactionid="505eeb9c43969d4919c0a6b3f7a4dfbb" messageid="a92eff8d65cf48e9c6e96702a7b07400"/>
</rsp>';
$stat = xmlRequestWasSuccessful($xml);
you will receive 'true' boolean in the result ($stat variable). Adapt it to support the case when there is an error. Since no details on how it looks when error occurs, this is how you can do it now:
if ($stat) {
// do something on success ('sent' something)
} else {
// do something on success (display 'unsent' message for example)
}

Categories