How to print an array element from JSON into PHP - php

If you access the webpage https://api.mercadolibre.com/items/MLB752465575 you will receive a JSON response. All I need to start is print the item "id" on the screen.
This is my code:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<?php
$json_str = "https://api.mercadolibre.com/items/MLB752465575";
$obj = json_decode($json_str);
echo "id: $obj->id<br>";
?>
</body>
</html>
All I want is receive the MLB752465575 part into my browser.
How can I do it?

$json_str = "https://api.mercadolibre.com/items/MLB752465575";
The above does not retrieve the data it's saving the url to the var and that's not what you want.
You just need to fetch the content You can use cURL or file_get_contents()
cURL version:
<?php
$url = "https://api.mercadolibre.com/items/MLB752465575";
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
$r = curl_exec($curl);
curl_close($curl);
$array = json_decode($r, true);
echo "<pre>";
print_r($array);
echo "</pre>";
?>
file_get_contents version:
<?php
$r = file_get_contents('https://api.mercadolibre.com/items/MLB752465575');
echo "<pre>";
echo print_r(json_decode($r, true));
echo "</pre>";
?>
Both of them will work unless the remote website requires you to be human (has extra verifications to stop robot requests). cURL would be a better way if that were the case because you can fake a user agent using a header array.
Once you have the array build it's just a matter of accessing the required data. using $r as an array result of the remote json structure.

Use curl to get the result, and json_decode to turn it into an array.
<?php
$url = "https://api.mercadolibre.com/items/MLB752465575";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($httpcode != 200) {
echo "error " . $httpcode;
curl_close($ch);
return -1;
}
$result_arr = json_decode($result, true);
echo $result_arr['id'];
curl_close($ch);

$jsonResponse = file_get_contents('https://api.mercadolibre.com/items/MLB752465575');
$obj = json_decode($jsonResponse);
echo "id: {$obj->id}<br>";
What you did in your code was to json_decode the URL itself. You needed to get the content from the URL, and then decode the content.

Related

Pulling instagram photos in php

I am going to pull my hair out. Can anyone please help me get this to work I am sure it's something stupid.. I have got all the PHP errors to go away, but I can not get images to show up. Code below...
<!DOCTYPE html>
<html>
<link rel="stylesheet" href="jquery.fancybox-1.3.4.css" type="text/css">
<script type='text/javascript' src='jquery.min.js'></script>
<script type='text/javascript' src='jquery.fancybox-1.3.4.pack.js'></script>
<script type="text/javascript">
$(function() {
$("a.group").fancybox({
'nextEffect' : 'fade',
'prevEffect' : 'fade',
'overlayOpacity' : 0.8,
'overlayColor' : '#000000',
'arrows' : false,
});
});
</script>
<?php
// Supply a user id and an access token
$userid = "1d458ab0c149424c812e664c32b48149";
$accessToken = "c195717e379f48c68df451cc3d60524a";
// Gets our data
function fetchData($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
// Pulls and parses data.
$result = fetchData("https://api.instagram.com/v1/users/{$userid}/media/recent/?access_token={$accessToken}");
$result = json_decode($result);
?>
<?php if(!empty($result->data)): ?>
<?php foreach ($result->data as $post){ ?>
<!-- Renders images. #Options (thumbnail,low_resoulution, high_resolution) -->
<a class="group" rel="group1" href="<?= $post->images->standard_resolution->url ?>"><img src="<?= $post->images->thumbnail->url ?>"></a>
<?php } ?>
<?php endif ?>
</html>
What you need is to add some checks at various points to find out what is coming back from Instagram and handle any issues. While debugging, sticking var_dump() all over the place can be helpful to see where issues lie.
Here is an example of your PHP section with some additional checks:
<?php
// Supply a user id and an access token
$userid = "USER ID";
$accessToken = "ACCESS TOKEN";
// Gets our data
function fetchData($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
$result = curl_exec($ch);
$info = curl_getinfo($ch);
// Check a response was returned
if ($info['http_code'] == '404') {
echo ('Error: HTTP 404 returned, bad request');
die();
}
curl_close($ch);
return $result;
}
// Pulls and parses data.
$result = fetchData("https://api.instagram.com/v1/users/{$userid}/?access_token={$accessToken}");
$result = json_decode($result);
// Check the json_decode succeeded
if (empty($result)) {
echo "Error: JSON not returned from API";
die();
}
// Check no error was returned from Instagram
if ($result->meta->code != 200) {
echo "Error: ".$result->meta->error_message;
die();
}
?>
If you plan on doing a lot of work with the Instagram API, you may want to look at a library to do most of the heavy lifting. This one appears to be the most popular at present.

Having trouble loading php curl results

So I'm having a problem with the following code.
I've got CURLOPT_RETURNTRANSFER set to true, yet nothing is returned when curl_exec is hit. Any and all help is appreciated!
<?php
$yql_base_url = "http://query.yahooapis.com/v1/public/yql?q=";
$yql_query = "select * from csv where url='http://download.finance.yahoo.com/d/quotes.csv?s=YHOO,GOOG,AAPL&f=sl1d1t1c1ohgv&e=.csv' and columns='symbol,price,date,time,change,col1,high,low,col2'";
$yql_params = "&format=json&diagnostics=true&callback=";
$yql_url = $yql_base_url . urlencode($yql_query) . $yql_params;
$session = curl_init($yql_url);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
$json = curl_exec($session);
curl_close($session);
$phpObj = json_decode($json);
if(!is_null($phpObj->query->results))
{
echo $phpObj->query->results;
}
?>
$phpObj->query->results is an array of Object and you can not do echo on it. Simply use print_r() or var_dump() on it.
Example:
print_r($phpObj->query->results);
var_dump($phpObj->query->results);

I am able to fetch the data from facebook in json format but not able to insert in the database.

The code is working fine but i am not able to insert the user data in the mysql database.
<?php
$facebookAppAuthUrl = 'https://graph.facebook.com/oauth/access_token';
$facebookGraphUrl = 'https://graph.facebook.com';
$facebookClientId = ''; // Put your App Id here.
$facebookRedirectUrl = ''; // Redirect url same as passed before.
$facebookAppSecret = ""; // Put your App Secret here.
$code = $_GET['code'];
$url =$facebookAppAuthUrl."?client_id=".$facebookClientId
."&redirect_uri=".$facebookRedirectUrl
."&client_secret=".$facebookAppSecret
."&code=".$code;
$output = urlResponse($url);
$var = strtok($output, "&");
$ApCode = strtok($var, "=");
$ApCode = strtok("=");
// This $ApCode will be used as a token to get user info from facebook.
$url = $facebookGraphUrl.'/me';
echo '<pre>';
$resposeObj = json_decode(processUrl($url,$ApCode));
var_dump($resposeObj);
echo '<pre>';
function urlResponse($url)
{
$ch = curl_init();
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
function processUrl($url,$apCode){
if(stripos($url,'?')>0)
$url = $url.'&access_token='.$apCode;
else
$url = $url.'?access_token='.$apCode;
return urlResponse($url);
}
?>
I guess the code below is wrong. I got the user data from facebook in JSON format but unfortunately I am not able to add user data in mysql using the PHP. How could we insert the json format data in mysql using php?
<?php
require('../conn.php');
$name = $url['id']['name'];
$first_name = $url['id']['first_name'];
$last_name = $url['id']['last_name'];
$hometown = $url['id']['hometown'];
{
$sql="insert into user values('','$name','$first_name','$last_name','$hometown')";
mysql_query($sql);
}
?>
<script type="text/javascript">window.location="../index.php"</script>
<html>
<head>
<title></title>
</head>
<body>
</body>
</html>
Here what you need to do , first the JSON returned data needs to be converted to array as
$response = json_decode($response,true);
Now with this data you have the array and you can use print_r($response) and see how the array looks like and use the data in the query.
Hope this helps
So, apparently I can't comment without 50 rep points - so whatever. I suspect your insert statement is off. Why do you have an empty string at the beginning? I hope that's not your primary key field. I would specify my fields if I were you and leave the auto-inc field out of it so it can auto increment :)
$sql="insert into user (`name`,`firstName`,`LastName`,`homeTown`) values('$name','$first_name','$last_name','$hometown')";

PHP GET Request return inconsistent results

I am using cURL via PHP to test service connections, and I'm getting some inconsistent results. When I run the test via PHP & cURL this is my result:
{"response":"\n\n\n\n \n \n
When I put that same URL in my browser I get this:
{"response":"\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n<head>\n <link href=\"/images/global/global.css\...and so on
The response in my browser is cut short, but you get the idea.
With my PHP, I read in a JSON file, parse out the URL I need and the use cURL to send a GET request. Here is the code that I am using to test the service via PHP:
<?php
include ("serviceURLs.php");
class callService {
function testService($url){
$ch = curl_init($url);
curl_exec($ch);
$info = curl_getinfo($ch);
if ($info['http_code'] == 200){
echo("Test has passed </br>");
}else{
echo("Test Failed.</br> ");
}
var_dump($info);
curl_close($ch);
}
function readFile(){
$myFile = "./service/catalog-adaptation.json";
$fr = fopen($myFile, 'r');
$fileData = fread($fr, filesize($myFile));
$json_a = json_decode($fileData, TRUE);
$prodServer = $json_a['serverRoots']['%SERVER_ROOT']['PROD'];
$demoServer = $json_a['serverRoots']['%SERVER_ROOT']['DEMO'];
$testServer = $json_a['serverRoots']['%SERVER_ROOT']['TEST'];
$testUrls = $json_a['commands'];
foreach($testUrls as $tURL){
$mURL = $tURL['URL'];
if(stripos($mURL, "%")===0){
$testTestService = str_replace("%SERVER_ROOT", $testServer, $mURL);
$testDemoService = str_replace("%SERVER_ROOT", $demoServer, $mURL);
$testProdService = str_replace("%SERVER_ROOT", $prodServer, $mURL);
echo ("Production test: ");
$this->testService($testProdService);
echo ("Demo test: ");
$this->testService($testDemoService);
echo ("Test test: ");
$this->testService($testTestService);
}
}
}
}
$newServiceTest = new callService;
$newServiceTest->readFile();
?>
Can anyone tell my why I am getting different results and how I can fix my code so I can get consistent results?
You need to set below option for return the transfer as a string of the return value of curl_exec() instead of outputting it out directly.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

PHP & Parsing a JSON response

I'm trying to play with a web service via REST.
I finally am getting the results I want (or at least I think I am), but am unaware what to do with it. The response format is JSON.. I try outputting it via json_decode() to get it as an array, then I could do something with it.
You can see that I am getting "something" as a response as I am echoing the url that I am CURL'ing
I know this is a matter of education, but this is my first jaunt at this, so any help is appreciated. Again, my end goal is to obviously output the data in a readable format.
<?php
if(isset($_GET['word']))
{
$result= get_response_json($_GET['word']);
} else {$result = "";}
function get_response_json($word)
{
$postURL = "http://rhymebrain.com/talk?function=getRhymes&word=".urlencode($word);
echo $postURL;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $postURL);
curl_setopt($ch, CURLOPT_HEADER, false);
//curl_setopt($ch, CURLOPT_POST, true);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
?>
<html>
<title>Test Rhyme</title>
<body>
<form action="<?=$_SERVER['PHP_SELF'];?>" method="get">
<input type="input" name="word" />
<input type="submit" value="Submit" />
</form>
<div id="results">
<?php
print_r(json_decode($result, true));
?>
</div>
</body>
</html>
Check here: http://php.net/manual/en/function.curl-exec.php. The one noteworthy thing I saw was this:
Returns TRUE on success or FALSE on failure. However, if the CURLOPT_RETURNTRANSFER option is set, it will return the result on success, FALSE on failure.
Note that there is a great example if you search for "curl_get(".
Here's an example:
$json = '[
{
"ID": "1001",
"Phone": "5555555555"
}
]';
$jsonArray = json_decode($json);
foreach($jsonArray as $value){
$id = $value->ID;
$phone = $value->Phone;
}
Here's a simplified way to do it without cURL
function get_response_json($word)
{
$postURL = "http://rhymebrain.com/talk?function=getRhymes&word=".urlencode($word);
$json = file_get_contents($postURL);
return $json;
}

Categories