i json_decode ed an array, even thought i can print_r it, i cant call its keys. Im not a pro nor nothing, so any help is welcome. I tried a lot of things, but i cant get it to work.
My goal is to present the array results i a way that is easy to read, so I want to access it in the HTML part, and not only to be printed.
the array that i get after print_r is: Array ( [0] => stdClass Object ( [pda] => 41.52258509711 [upa] => 51.345212698165 [uu] => www.chevrolet.com.ar/ ) )
<?php
$accessID = "xxxxx";
$secretKey = "xxxxx";
// Set your expires times for several minutes into the future.
// An expires time excessively far in the future will not be honored by the Mozscape API.
$expires = time() + 300;
// Put each parameter on a new line.
$stringToSign = $accessID."\n".$expires;
// Get the "raw" or binary output of the hmac hash.
$binarySignature = hash_hmac('sha1', $stringToSign, $secretKey, true);
// Base64-encode it and then url-encode that.
$urlSafeSignature = urlencode(base64_encode($binarySignature));
$cols = "103079215108";
// Put it all together and you get your request URL.
$requestUrl = "http://lsapi.seomoz.com/linkscape/url-metrics/?Cols=".$cols."&AccessID=".$accessID."&Expires=".$expires."&Signature=".$urlSafeSignature;
// Put your URLS into an array and json_encode them.
$batchedDomains = array('xxxxxxxx.com');
$encodedDomains = json_encode($batchedDomains);
// Use Curl to send off your request.
// Send your encoded list of domains through Curl's POSTFIELDS.
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => $encodedDomains
);
$ch = curl_init($requestUrl);
curl_setopt_array($ch, $options);
$content = curl_exec($ch);
curl_close( $ch );
$contents = json_decode($content);
print_r($contents);
$pageAuthority=$contents->upa;
$domainAuthority = $contents->pda;
$theUrl = $contents->uu;
?>
<html>
<body>
<h1>MOZcape API</h1>
<ul>
<li>URL: <?php echo $theUrl; ?></li>
<li>PA: <?php echo $pageAuthority; ?></li>
<li>DA: <?php echo $domainAuthority; ?></li>
</ul>
</body>
</html>
Just had to change $contents = json_decode($content);
to $contents = json_decode($content, true); so it can be an array.
Then call it with:$pageAuthority=$contents[0]["upa"];
Instead of:$pageAuthority=$contents->upa;
Related
For my project, i'm trying to get the post request on my index.php, edit it with some random values, and then redirect it to another page.
I tried the following:
----------- POST REQUEST -----------
Array
(
[authToken] => 0a65e943412453ecec35c814
[sessionId] => 431503466924
[answers] => [{"Boost":false,"answerTime":1300,"id":3},{"Boost":false,"answerTime":800,"id":1},{"Boost":false,"answerTime":900,"id":3},{"Boost":false,"answerTime":1000,"id":1},{"Boost":false,"answerTime":1200,"id":1}]
[userId] => 2235
)
----------- POST REQUEST -----------
My index.php
<?php
$time=[800,900,1000,1100,1200,1300,1500];
$array = json_decode($_POST['answers'], true);
foreach($array as &$k)
{
$k['answerTime'] =$time[array_rand($time)];
}
$postpop = json_encode($array);
$url = 'http://127.0.0.1/index2.php';
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,count($postpop));
curl_setopt($ch,CURLOPT_POSTFIELDS,$postpop);
$result = curl_exec($ch);
curl_close($ch);
?>
By doing that, i only get the [answers] on my response.
How can i get to recompile the full request?
It looks like you are simply failing to reassemble all the parts. Store the POST, manipulate the answer element, and then replace that part.
<?php
$time = [800,900,1000,1100,1200,1300,1500];
//Store the full post as received.
$originalPost = $_POST;
$array = json_decode($_POST['answers'], true);
foreach($array as &$k) {
$k['answerTime'] = $time[array_rand($time)];
}
//replace just the part of the array we manipulated
$originalPost['answers'] = json_encode($array);
$url = 'http://127.0.0.1/index2.php';
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,count($originalPost));
curl_setopt($ch,CURLOPT_POSTFIELDS,$originalPost);
$result = curl_exec($ch);
curl_close($ch);
So i'm trying to get location usng reverse geocoding
https://developers.google.com/maps/documentation/geocoding/#ReverseGeocoding
so my question is (since i'm very new to php) how to get the result from URL into parameter (the result will be json encoded data)
you can use function file_get_contents to get Data from URL
$API_KEY ="XXXXXXX";
$url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&key=".$API_KEY;
$data = #file_get_contents($url);
$jsondata = json_decode($data,true);
if(is_array($jsondata) && $jsondata['status'] == "OK")
{
echo '<pre>'; print_r($jsondata);echo '</pre>';
}
To get the data we use the PHP curl functions.
[php]
// jSON URL which should be requested
$json_url = ‘www.yourdomain.com';
$username = ‘your_username'; // authentication
$password = ‘your_password'; // authentication
// jSON String for request
$json_string = ‘[your json string here]';
// Initializing curl
$ch = curl_init( $json_url );
// Configuring curl options
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_USERPWD => $username . “:” . $password, // authentication
CURLOPT_HTTPHEADER => array(‘Content-type: application/json’) ,
CURLOPT_POSTFIELDS => $json_string
);
// Setting curl options
curl_setopt_array( $ch, $options );
// Getting results
$result = curl_exec($ch); // Getting jSON result string
[/php]
The result will be a jSON string.
Normally you have to send a jSON string to the jSON URL and you will get a jSON string back. To encode your data, just use the php jSON functions. Use json_encode to create a json string from your PHP array and use json_decode to transform the jSON string to PHP array.
I´m currently trying to get all the URLs for my pictures from my instagram feed and print them out in a simple HTML gallery.
I have managed with "some help" to authenticate and get an accesstoken which allows me to get a JSON result containing all my pictures, but I´m totally new to how to fetch all the pictures with the help of JSON.
The code I've got so far looks like this:
<?php
session_start();
//require_once 'src/config.php';
$n_client_id = '87fdd319f8244a728a86f3692527fb15';
$n_client_secret = '040d431d4e0247a292612229446b5240';
$n_redurect_uri = 'http://ideweb2.hh.se/~lukpal12/Startsida.php';
//require_once 'src/Instagram.php';
date_default_timezone_set('UTC');
$url = "https://api.instagram.com/oauth/access_token";
$access_token_parameters = array(
'client_id' => $n_client_id,
'client_secret' => $n_client_secret,
'grant_type' => 'authorization_code',
'redirect_uri' => $n_redurect_uri,
'code' => $_GET["code"]
);
$curl = curl_init($url);
curl_setopt($curl,CURLOPT_POST,true);
curl_setopt($curl,CURLOPT_POSTFIELDS,$access_token_parameters);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($curl);
$authObj = json_decode($result);
print_r($result);
$instagram = <<<END
Get pictars!
END;
echo $instagram;
echo $authObj->access_token;
?>
Since I'm completely new to JSON and how to work with it, I have no idea how the code should be written to do what I'm asking.
After some searching around and after a video or two explaining JSON I managed to get this code to do the Json_decode:
$json = file_get_contents("https://api.instagram.com/v1/users/2912979/media/recent/?access_token=2912979.87fdd31.0949d22f4a714349ae84643c5af165ef");
$data = json_decode($json);
echo $data->standard_resolution[0]->url;
But that does not work at all. I've got the link to the JSON containing all the data here:
https://api.instagram.com/v1/users/2912979/media/recent/?access_token=2912979.87fdd31.0949d22f4a714349ae84643c5af165ef
If someone would be kind enough to help me out.
First loop will give an array of images with all resolutions, while the second one an array with only standard_resolutions, use print_r to inspect the arrays.
$json = file_get_contents("https://api.instagram.com/v1/users/2912979/media/recent/?access_token=2912979.87fdd31.0949d22f4a714349ae84643c5af165ef");
$data = json_decode($json);
// to get the array with all resolutions
$images = array();
foreach( $data->data as $user_data ) {
$images[] = (array) $user_data->images;
}
// print_r( $images );
// to get the array with standard resolutions
$standard = array_map( function( $item ) {
return $item['standard_resolution']->url;
}, $images );
// print_r( $standard );
EDIT
To put these images to a gallery use foreach loop. See the PHP manual on how to use an array.
foreach( $standard as $url ) {
echo "<img src=\"$url\">";
}
This is the function I use to grab a JSON file from Feedbin API.
<?php
error_reporting(E_ALL);
// JSON URL which should be requested
$json_url = 'https://api.feedbin.me/v2/entries.json';
$username = 'my_username'; // authentication
$password = ' my_password'; // authentication
// Initializing curl
$ch = curl_init( $json_url );
// Configuring curl options
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_USERPWD => $username . ":" . $password // authentication
);
// Setting curl options
curl_setopt_array( $ch, $options );
// Getting results
$result = curl_exec($ch); // Getting JSON result string
print_r ($result);
?>
Problem is the JSON I get is a bit.. strange.
It has a lot of chars like \u003E\u003C/a\u003E\u003C/p\u003E\n\u003Cp\u003E ...
You can see the JSON here.
When you call json_decode in PHP on strings that contain these encodings they will be correctly decoded. http://json.org/ lists \ufour-hex-digits as a valid character. There is no issue.
$ echo json_decode('"\u003E\u003C/a\u003E\u003C/p\u003E\n\u003Cp\u003E"');
></a></p>
<p>
They are valid unicode sequence. Here is a simple example
$data = array(
"abc" => 'åbcdéfg'
);
// Encode
$data = json_encode($data) . "\n";
// Output Value
echo $data;
// Output Decoded Value
print_r(json_decode($data));
Output
{"abc":"\u00e5bcd\u00e9fg"}
stdClass Object
(
[abc] => åbcdéfg
)
Hey I'm having some issues using cURL (I can't use file_get_contents because my web host won't allow it) to access parts of the wunderground weather api.
When I use the following code to access info on weather conditions I have no issues whatsoever:
<? $json_url = 'http://api.wunderground.com/api/b2b4a1ad0a889006/geolookup/conditions
/q/IA/Cedar_Rapids.json';
// jSON String for request
$json_string = '[http://api.wunderground.com/api/b2b4a1ad0a889006/geolookup/conditions
/q/IA/Cedar_Rapids.json]';
// Initializing curl
$ch = curl_init( $json_url );
// Configuring curl options
$options = array(
CURLOPT_RETURNTRANSFER => true,
);
// Setting curl options
curl_setopt_array( $ch, $options );
// Getting results
$result = curl_exec($ch); // Getting jSON result string
$parsed_json = json_decode($result);
$location = $parsed_json->{'location'}->{'city'};
$temp_f = $parsed_json->{'current_observation'}->{'temp_f'};
echo "Current temperature in ${location} is: ${temp_f}\n";
?>
However, when I make slight modifications in order to get data on high and low tides using the following code I get nothing:
<? $json_url = 'http://api.wunderground.com/api/b2b4a1ad0a889006/tide/q/NJ/Wildwood.json';
// jSON String for request
$json_string = '[http://api.wunderground.com/api/b2b4a1ad0a889006/tide/q/NJ/Wildwood.json]';
// Initializing curl
$ch = curl_init( $json_url );
// Configuring curl options
$options = array(
CURLOPT_RETURNTRANSFER => true,
);
// Setting curl options
curl_setopt_array( $ch, $options );
// Getting results
$result = curl_exec($ch); // Getting jSON result string
$tide_time = $parsed_json->{'tide'}->{'tideSummary'}->{'date'}->{'pretty'};
echo "High tide is at ${tide_time} ";
?>
Now I know the issue may be that I'm dealing with an array in the second example but I'm not sure how to modify the code. I know that the record for the first low tide is [3] and I've tried making the following modification with no luck.
$tide_time = $parsed_json->{'tide'}->{'tideSummary'}->[3]->{'date'}->{'pretty'};
echo "High tide is at ${tide_time} ";
Any help would be greatly appreciated!
The second parameter of json_decode allows you to decode the JSON into an array instead of an object. Try turning that on so you always know what you're dealing with:
$response = json_decode($result, true);
If that fails maybe you're not using the API correctly?