im new to php, I want to get many data and output them from different urls, so actually I made one that works and gets one data.. so far I have searched and looked so many.. but I couldn't figure how to get multiples ones..
so one thing to consider : that yellow text I have highlighted has more than 100.. i mean eid=1 to eid=102.. each one has data stored in it.
my php code is this
<?php
$eType=2;
$eId=43;
$lType=1;
$dNames=drivername;
$shard="Apex";
$session = curl_init();
curl_setopt ($session, CURLOPT_URL, "http://world.needforspeed.com/SpeedAPI/ws/game/nfsw/leaderboards?output=xml");
curl_setopt ($session, CURLOPT_POST, true);
curl_setopt ($session, CURLOPT_POSTFIELDS, "et=".$eType."&eid=".$eId."<=".$lType."&dn=".$dNames."&shard=".$shard);
curl_setopt ($session, CURLOPT_HEADER, true);
curl_setopt ($session, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($session);
curl_close($session);
// Get the XML from the response, bypassing the header
if (!($xml = strstr($response, '<?xml'))) {
$xml = null;
}
// Output the XML
$worldLeaderboard = simplexml_load_string($xml);
foreach ($worldLeaderboard->worldLeaderboard as $world){
$rank = $world['rank'];
$name = $world['personaName'];
$car = $world['make'];
$model = $world['carName'];
$duration = $world['eventDuration'];
echo <<<EOD
$rank $name $car $model $duration
EOD;
}
?>
as you can see my code, it works fine and outputs from that data.. I know I can do multiple by coping all the code and pasting it 100 times, and changing each $eid variable value but that's too much and data consuming I assume..
Make a function for the curl calls, put the URLs in an array and loop through the array and use each entry in the array on the curl function you wrote.
function my_curl_function($url)
{
// curl call
return $result;
}
$urls[] = 'url1';
$urls[] = 'url2';
$urls[] = 'url3';
// etc
foreach($urls AS $url)
{
echo my_curl_function($url);
}
You could use a simple 'for' loop.
for($eId=1;$eId<=102;$eId++) {
$eType=2;
$lType=1;
$dNames=drivername;
$shard="Apex";
$session = curl_init();
curl_setopt ($session, CURLOPT_URL, "http://world.needforspeed.com/SpeedAPI/ws/game/nfsw/leaderboards?output=xml");
curl_setopt ($session, CURLOPT_POST, true);
curl_setopt ($session, CURLOPT_POSTFIELDS, "et=".$eType."&eid=".$eId."<=".$lType."&dn=".$dNames."&shard=".$shard);
curl_setopt ($session, CURLOPT_HEADER, true);
curl_setopt ($session, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($session);
curl_close($session);
// Get the XML from the response, bypassing the header
if (!($xml = strstr($response, '<?xml'))) {
$xml = null;
}
// Output the XML
$worldLeaderboard = simplexml_load_string($xml);
foreach ($worldLeaderboard->worldLeaderboard as $world){
$rank = $world['rank'];
$name = $world['personaName'];
$car = $world['make'];
$model = $world['carName'];
$duration = $world['eventDuration'];
echo <<<EOD
$rank $name $car $model $duration
EOD;
}
}
Related
When i am Decoding using commented "$jsonString" String it is working very well.
But after using curl it is not working, showing Null.
Please Help Me in this.
if (isset($_POST['dkno'])) {
$dcktNo = $_POST['dkno'];
$url = 'http://ExampleStatus.php?dkno=' . $dcktNo;
$myvars = '';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $myvars);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$jsonString = curl_exec($ch);
// $jsonString = '[{"branchname":"BHUBNESHWAR","consignee":"ICICI BANK LTD","currentstatus":"Delivered by : BHUBNESHWAR On - 25/07/2015 01:00","dlyflag":"Y","PODuploaded":"Not Uploaded"}]';
if ($jsonString != '') {
$json = str_replace(array('[', ']'), '', $jsonString);
echo $json;
$obj = json_decode($json);
if (is_null($obj)) {
die("<br/>Invalid JSON, don't need to keep on working on it");
} else {
$podStatus = $obj->PODuploaded;
}
}
}
}
After curl I used following concept to get only JSON data from HTML Page.
1) fetchData.php
$url = 'http://DocketStatusApp.aspx?dkno=' . $dcktNo;
$myvars = '';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $myvars);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$jsonString = curl_exec($ch);
// now get only value
$dom = new DOMDocument();
$dom->loadHTML($jsonString);
$thediv = $dom->getElementById('Label1');
echo $thediv->textContent;
2) JSONprocess.php
if (isset($_POST['dkno'])) {
$dcktNo = $_POST['dkno'];
ob_start(); // begin collecting output
include_once 'fetchData.php';
$result = ob_get_clean(); // Completed collecting output
// Now it will show & take only JSON Data from Div Tag
$json = str_replace(array('[', ']'), '', $result);
$obj = json_decode($json);
if (is_null($obj)) {
die("<br/>Invalid JSON, don't need to keep on working on it");
} else {
$podStatus = $obj->PODuploaded;
}
}
This is one of my first curls code, so it can have mistakes
I'm trying to be able to make calls to form/:id/submissions
https://www.formstack.com/developers/api/resources/submission#form/:id/submission_GET
If I load:
https://www.formstack.com/api/v2/form/1311091/submission.json?oauth_token=abc&min_time=2012-09-01%2000:01:01&max_time=2012-10-27%2000:01:01
If works great.
If I try this code:
<?php
$host = 'https://www.formstack.com/api/v2/';
// TODO this should manage dinamics values or build an action in every method.
$action = 'form/1311091/submission.json';
$url = $host . $action;
// TODO this values will arrive like an array with values
$postData['oauth_token']= 'abc';
$postData['min_time'] ='2012-09-01 00:01:01';
$postData['max_time'] ='2012-10-27 00:01:01';
// TODO make a method with this action
function getElements($postData)
{
$elements = array();
foreach ($postData as $name=>$value) {
$elements[] = "{$name}=".urlencode($value);
}
}
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPGET, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $elements);
$result = curl_exec($curl) ;
curl_close($curl);
var_dump($result);
?>
You'll need to set:
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
As an option before curl_exec() if you wish to get data back.
CURLOPT_RETURNTRANSFER: TRUE to return the transfer as a string of the
return value of curl_exec() instead of outputting it out directly.
Also, why are you trying to send POST data via a GET request?
CURLOPT_POSTFIELDS: The full data to post in a HTTP "POST" operation.
Also, for debugging, you should check out:
echo curl_error ( $curl );
This works for me:
<?php
$host = 'https://www.formstack.com/api/v2/';
$action = 'form/1311091/submission.json';
$url = $host . $action;
$postData = array();
$postData['oauth_token']= 'REPLACE_WITH_TOKEN';
$postData['min_time'] ='2012-09-01 00:01:01';
$postData['max_time'] ='2012-10-27 00:01:01';
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
$result = curl_exec($curl);
curl_close($curl);
var_dump($result);
?>
I want to read XML data from a URL. I have the URL as follows:
http://www.arrowcast.net/fids/mco/fids.asp?sort=city&city=&number=&airline=&adi=A
Here is my code:
$Url="http://www.arrowcast.net/fids/mco/fids.asp?sort=city&city=&number=&airline=&adi=A";
if (!function_exists('curl_init')){
die('Sorry cURL is not installed!');
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $Url);
$output = curl_exec($ch);
$resultCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// Close the cURL resource, and free system resources
curl_close($ch);
Could anyone please tell me how to read xml data?
Here is some sample code (XML parsing module may not be available on your PHP installation):
<?php
$url="http://www.arrowcast.net/fids/mco/fids.asp?sort=city&city=&number=&airline=&adi=A";
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url); // get the url contents
$data = curl_exec($ch); // execute curl request
curl_close($ch);
$xml = simplexml_load_string($data);
print_r($xml);
?>
The variable $xml now is a multi-dimensional key value array and you should easily be able to figure out how to get the elements from there.
// the SAX way:
XMLReader myReader = XMLReaderFactory.createXMLReader();
myReader.setContentHandler(handler);
myReader.parse(new InputSource(new URL(url).openStream()));
// or if you prefer DOM:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new URL(url).openStream());
This is the demo of how to get channel id from rss feed of youtube in which i read xml data from url using curl.
$channel_id = 'XXXXXXXX'; // put the channel id here
//using curl
$url = 'https://www.youtube.com/feeds/videos.xml?channel_id='.$channel_id.'&orderby=published';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
//curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
$response = curl_exec($ch);
curl_close($ch);
$response=simplexml_load_string($response);
$json = json_encode($response);
$youtube= json_decode($json, true);
$count = 0;
if(isset($youtube['entry']['0']) && $youtube['entry']['0']!=array())
{
foreach ($youtube['entry'] as $k => $v) {
$yt_vids[$count]['id'] = str_replace('http://www.youtube.com/watch?v=', '', $v['link']['#attributes']['href']);
$yt_vids[$count]['title'] = $v['title'];
$count++;
}
}
else
{
$yt_vids[$count]['id']=str_replace('http://www.youtube.com/watch?v=', '', $youtube['entry']['link']['#attributes']['href']);
$yt_vids[$count]['title']=$youtube['title'];
}
echo "<pre>";
print_r($yt_vids);
My question is simple, but for me, it is creating so many confusions in my mind. I want to know that can we input an array to curl function ?
please note that 'I AM NOT POSTING DATA' (FOR POSTING DATA , I KNOW, ARRAY IS USED)
To make my question more clear, let me tell you the code ..
function mycurl($url){
$ch = curl_init(); // create a new cURL resource
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$data = curl_exec($ch); // grab URL and pass it to the browser
//echo $data; //ncomment for debugging
curl_close($ch);
return $data;
}
and array i am going to use is
myArray
0 => string 'http://www.abc.com/a
1 => string 'http://www.abc.com/b
2 => string 'http://www.abc.com/c
3 => string 'http://www.abc.com/d
to use the array, I am using foreach loop the code is given below
foreach ($myArray as $temp){
$heading= mycurl($temp);
echo $heading;
}
the purpose of the code is
go to each url of array using curl function extract required
data from the url process the next element of array and extract
data and so on
Can anybody guide me that How can i use array elements in curl function?
How can i get my objective? If foreach loop is not the correct methodology here, then what should I do?
What your doing looks good, except, you shouldn't initialize the curl handler for every iteration, just initialize it once, then change the $url value for every iteration, would look something like:
function mycurl($ch, $url) {
curl_setopt($ch, CURLOPT_URL,$url);
return curl_exec($ch);
}
$ch = curl_init(); // create a new cURL resource
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
foreach ($urls as $url) {
$header = mycurl($ch, $url);
var_dump($header);
}
curl_close($ch);
You're doing it right. However you can use curl_multi_exec() (see examples) to launch all requests at once, classical curl can do only one request at the time.
Little more effective way to do your code would be:
$ch = curl_init(); // create a new cURL resource
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
foreach( $myArray as $url){
curl_setopt($ch, CURLOPT_URL,$url);
$data = curl_exec( $ch);
echo $data;
}
curl_close( $ch);
Or with correct object design:
class MyClass {
protected $ch = null;
public function __construct( ){
$this->ch = curl_init();
curl_setopt($this->ch, CURLOPT_HEADER, 0);
curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, TRUE);
}
public function __destruct(){
curl_close( $this->ch);
}
public function getData( $url){
curl_setopt($this->ch, CURLOPT_URL,$url);
return curl_exec( $this->ch);
}
}
$extractor = new MyClass();
foreach( $myArray as $url){
$data = $extractor->getData( $url);
echo $data;
}
I tried to use JSON decode to get the youtube API feed. However, when I paste the JSON result in http://www.jsonlint.com/ I noticed something like
"media$group": {
"media$category": [
Unfortunately some symbols are rejected by php. Here is my code, I tried to remove this $ symbol, but maybe not success. How do I solve this?
$url = 'http://gdata.youtube.com/feeds/api/videosq=football&orderby=published&v=2&alt=json';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_REFERER, $url);
$body1 = curl_exec($ch);
$body = str_replace('$','', $body1);
curl_close($ch);
$data = json_decode($body);
foreach ($data->feed->entry as $result) {
...
}
Your problem is the usage of PHP identifiers to access the contents. The simplest solution here would be to get an array instead of an object:
$data = json_decode ( $json , $assoc = true );
This allows access to fields with:
echo $result['media$group']['media$description'];
If you want to keep the object syntax, that's possible with this kludge:
echo $result->{'media$group'}->{'media$category'};
(But arrays are safer here. You don't get a fatal error should the format change and properties be absent.)
This work:
<?php
$url = 'http://gdata.youtube.com/feeds/api/videos?q=football&orderby=published&v=2&alt=json';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_REFERER, $url);
$body1 = curl_exec($ch);
$body = str_replace('$','', $body1);
curl_close($ch);
$data = json_decode($body);
foreach ($data->feed->entry as $result) {
var_dump($result);
}
?>