I have the following data I pulled from an API using PHP's file_get_contents($url), I would like to parse this data and put each comma separated value into a variable whilst looping to the next set (there are thousands of row, I simply extracted the first two), I have tried parsing methods however most have an element consisting of the datalabel:data, any assistance would be gladly appreciated.
[[1610223840000,"3.63410000","3.65100000","3.62900000","3.64150000","14194.01000000",1610223899999,"51684.84892800",195,"7619.89000000","27756.15839400","0"],[1610223900000,"3.64610000","3.65090000","3.63410000","3.65000000","2219.73000000",1610223959999,"8090.68646600",46,"1176.75000000","4290.44934900","0"]]
Ok figured this out today, for anyone who needs it
$ch = curl_init();
$url = "https://api.blahblahblah";
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);
$result = curl_exec($ch);
curl_close($ch);
$obj = json_decode($result, true);
foreach ($obj as $key => $value) {
echo $value[0] . "<br>";
echo $value[1] . "<br>";
}
Related
I want to send data from server 1 to server 2, first I select necessary data from the database, but how to send data with curl? I understand that I cannot send $result parameter just like in my code, but how should I do this?
My Code server 1:
public function setDivisions(){
$result = $this->conn->query("SELECT *FROM data_divisions");
$ch = curl_init('https://example.com/api.php?siteid='.$this->site_key.'');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $result);
curl_setopt($ch, CURLOPT_POST, 1);
$response = curl_exec($ch);
print_r($response);
}
Code on server 2:
$array = $_POST['result'];
//loop throw array and insert data into database
you can use it that way.
$ch = curl_init('https://upxxx.cod3fus1ontm.com/curl/json');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode((object)["records" => json_encode($result)]));
$response = curl_exec($ch);
var_dump($response);
on receipt, like this!
$json = file_get_contents("php://input");
$content = json_decode($json, true);
$records = json_decode($content['records'], true);
foreach($records as $record) {
echo $record['id'] . " - " . $record['text'] . "<br/>";
}
remember, that as you did to encode, you will have to do to decode
Come on, php://input returns all raw data after the request's HTTP headers, regardless of content type.
When we do this with file_get_contents (which reads the contents of a file and puts it into a variable of type string), we can read the content that was sent by curl.
Reviewing the code, you can optimize as follows, when sending to the server you placed, I suggested:
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode((object)["records" => json_encode($result)]));
you can replace it with:
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($result));
it's much simpler, but it's very important to put the query result inside a json_encode
finally, you can access the entire body of the message, through file_get_contents ("php://input") and put it inside a variable, which is nothing more than a JSON of the your query.
for you to understand how the parameters were passed, it is interesting to do the following:
$json = file_get_contents("php: // input");
var_dump($json); <- Here you see the thing as it is.
$records = json_decode($json, true); <- Here you generate an object with the content of json
var_dump($records);
With that, I think that solves the situation.
on server 1
$result = "result=".base64_encode($result)
curl_setopt($ch, CURLOPT_POSTFIELDS, $result);
...
on server 2
$array = base64_decode($_POST['result']);
I'm new to programming, and I've made a page using PHP that lets us enter userIDs and add observers using the Canvas API and that worked great. I'm now trying to enter a list of people to be observed and have it process multiple URLs and this is where I'm running into problems. It only seems to process the final userID in the box.
Any ideas what I'm doing wrong? This doesn't need to be run often and I'm not worried about performance so I don't really need the cURL commands to process simultaneously.
$observeeA = explode ("\n", $observee);
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
foreach ($observeeA as $ob2){
if ($idtype == "Canvas") {
$url = $domain . "/api/v1/users/$observer/observees/" . $ob2; }
else {
$url = $domain . "/api/v1/users/sis_user_id:$observer/observees/sis_user_id:" . $ob2; }
curl_setopt($ch, CURLOPT_URL, $url);
$resp = curl_exec($ch);
echo $ob2 . "<br>" . $url . "<br>" . $resp . "<br>";
}
curl_close($ch);
The echo on line 13 outputs all the correct entries for the URL, but it never gets a response until the last one in the list.
It turns out that storing the string into the array with the explode function included extra hidden return characters, so I added $ob2 = trim($ob2); into the foreach loop and it now works.
I have a url like this, that search something in a location:
https://maps.google.com/maps?q=dentist+Austin+Texas&hl=en&mrt=yf=l
I need a list of the first 2 results like (“Dentist Mr.Example1”,”Dentist Ex.2”).
Watching this question: What parameters should I use in a Google Maps URL to go to a lat-lon? , I think the url is correct.
And watching this one: Get latitude and longitude automatically using php, API
I try this two options:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_PROXYPORT, 3128);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$response = curl_exec($ch);
curl_close($ch);
$response_a = json_decode($data);
and also this:
$content= file_get_contents($url);
preg_match_all("|<span class=\"pp-place-title\">(.*?)</span></span>|",$content,$result);
In both case I have no results at all.
Thanks in advance!
I have a url like this, that search something in a location:
https://maps.google.com/maps?q=dentist+Austin+Texas&hl=en&mrt=yf=l
I need a list of the first 2 results like (“Dentist
Mr.Example1”,”Dentist Ex.2”).
This is a Google Maps API Request.
Here you go:
$searchTerm = 'dentist+austin+texas';
$url = 'https://maps.googleapis.com/maps/api/geocode/json?address=' . $searchTerm;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$response = curl_exec($ch);
curl_close($ch);
$array = json_decode($response, true);
// var_dump($array);
// Output
$array = $array['results'];
foreach($array as $index => $component)
{
echo '#' . $index . ' ' . $component['formatted_address'] . '<br>';
// show only the first 2 items (#0 & #1)
if($index === 1) {
break;
}
}
Some notes:
Your search term is "dentist Austin textas" and that becomes 'dentist+austin+texas' when it's part of an URL.
The searchTerm is attached to the API URL.
This URL is used for the cURL request.
The raw response is $response.
This is turned into an $array by setting the second paramter of json_decode() to true.
You might var_dump() the array to see the keys. Or simply call this URL in a browser: https://maps.googleapis.com/maps/api/geocode/json?address=dentist+austin+texas
For the display part: that's a simply array iteration. You can get rid of the top-level 'results' array by re-assigning the values to $array.
The output is a numbered list of dentists
Referencing: https://developers.google.com/maps/documentation/geocoding/
This is almost perfect, but I would like to get also the phone number and the ranking (stars for reviews).
The initial question was to list the first to results for dentists in austin,tx using the Google Maps API.
This additional requirement changes the API / webservice to use, in order to retrieve rich data. You want more details about the addresses.
The data elements "phone_number" and "rating" are part of the Google Places Webservice (Place Details). You need to add your key to the request URLs (&key=API_KEY) in order to access this service.
https://developers.google.com/places/webservice/details#PlaceDetailsRequests
This is a Place Detail Requests:
1) From the first request you extract the "place_id"s.
2) With subsequent requests you retrieve the details about each place via the "Place Details" webservice.
Example: here i'm using the placeid for the first entry:
https://maps.googleapis.com/maps/api/place/details/json?placeid=ChIJ0aPBm9xLW4YRLBdfVhz_2P0&key=AIzaSyCj9yH5x6_5_Om8ebAO2pBlaqJZB-TIViY
New code:
<?php
// Google GeoCode API
$address = 'dentist+austin+texas';
$array = getGoogleGeoCode($address);
$array = $array['results'];
//var_dump($array);
foreach($array as $index => $component)
{
echo '#' . $index . ' ' . $component['formatted_address'] . ', ' ;
// subsequent request for "Place Details"
$details = getGooglePlaceDetails($component['place_id']);
$details = $details['result'];
//var_dump($details);
echo 'Phone: ' . $details['formatted_phone_number']. ', ' ;
// rating contains the place's rating, from 1.0 to 5.0, based on aggregated user reviews.
if(isset($details['rating'])) {
echo 'Rating: ' . $details['rating'];
}
// show only the first two entries
/*if($index === 1) {
break;
}*/
echo '<br>';
}
function getGooglePlaceDetails($placeid)
{
// your google API key
$key = 'AIzaSyCj9yH5x6_5_Om8ebAO2pBlaqJZB-TIViY';
$url = 'https://maps.googleapis.com/maps/api/place/details/json?placeid=' . $placeid . '&key=' . $key;
return curlRequest($url);
}
function getGoogleGeoCode($address)
{
$url = 'https://maps.googleapis.com/maps/api/geocode/json?address=' . $address;
return curlRequest($url);
}
function curlRequest($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$response = curl_exec($ch);
curl_close($ch);
return json_decode($response, true);
}
Result:
The array element rating is not always present, because it's review based. Just use var_dump($details); to see what is there and pick what you need.
To reduce the list, remove the comments around the break statement.
Im stumbling upon issues I find hard to explain myself. I have this code that usually works perfectly fine, but after I change to nested information the result always lead to Fatal error: Cannot use string offset as an array. Even if I revert everything to the old state, it keeps telling me the fatal error. I am using the RIOT API (league of legends).
<?php
ini_set("display_errors", "1"); error_reporting(E_ALL);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://euw.api.pvp.net/api/lol/euw/v2.5/league/challenger?type=RANKED_SOLO_5x5&api_key=key');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($ch);
curl_close($ch);
$json = json_decode($response, true);
foreach($json as $elem)
{
echo $elem[0]['entries'][0]['playerOrTeamName'];
// echo $elem[0]['entries'][0]['miniSeries'][0]['wins'];
// echo $elem[0]['entries'][0]['miniSeries'][0]['losses'];
}
?>
You have not explored array properly.
foreach ($json['entries'] as $entry)
{
echo $entry['playerOrTeamName'] . ' wins:' . $entry['wins'] . "<br/>";
}
Also, your array does not contain losses, and miniSeries.
Please, explore your data thoroughly further.
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