Decode a Json string - php

Was wondering how i'd be able to extract the index part of the json in php.
Has been bugging me for ages. Thanks!
$ch = curl_init('https://domain.com/blah/blah');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$promo = curl_exec($ch);
curl_close($ch);
$promo = json_decode($promo, true);
.
{"something":"blahhhh","name":"bob!","id":"7","select":[{"Index":1,"code":"a1","name":"hello","description":"more text"},{"Index":2,"code":"a2","name":"bye","description":"test.."},{"Index":3,"code":"a3","name":"ayeee","description":"Morning!"},{"Index":4,"code":"a4","name":"Cheese!","description":"Yummy!"},{"Index":5,"code":"a5","name":"Water","description":"why is it cloudy? :( "}],"chant":"Free the ducks!","joined":"2015-01-01T16:49:05.000+0000","cool":false}

When the 2nd parameter of json_decode is set to true the function return an associative array who's really close to the structure of the JSON.
From there all what you got to do is put back the JSON path into an associative php array to access the wanted value !
foreach($promo['select'] as $select){
echo $select['Index'].' ';
}
example : http://codepad.org/OMg7WTr0
If you're looking to extract other value and you don't figure out the path just do var_dump($promo); it will give you a clear view of the array path to use

Related

Sending array using curl

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']);

GET a JSON Array with an API in PHP?

Basically I'm trying to GET an API that gives me a JSON array. It should only be one integer. Whenever I try to though I receive the error:
Notice: Trying to get property of non-object in /public_html/call.php on line 16
Here's call.php:
<?php
require 'connection.php';
$players2weeks = '(removed api)';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $players2weeks);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$response = curl_exec($ch);
curl_close($ch);
$response = json_decode($response);
print_r($response);
echo $response->players_2weeks;
?>
I have the print_r for troubleshooting but I'm getting nothing. My apologies for a noob question by the way, I have no experience with JSON.
Appreciate the help!
I think you can use this Code :
<?php
require 'connection.php';
$players2weeks = '(removed api)';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $players2weeks);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$response = curl_exec($ch);
curl_close($ch);
$responses = json_decode($response);
print_r($responses);
echo $responses['players_2weeks'];
?>
You should change the format of echo when the decoded JSON objects. and the Variable same means some clashes in the print so I changed the $response variable also...
You have to make array to json string by using the json_encode() function on the api.
For example: xxx.php (api)
$result = array(); //return array
echo json_encode($result);
Then you can get result by json array on the api caller.
var_dump(json_decode($result)); // Object
var_dump(json_decode($result, true)); // Associative array

using json data from Curl response

Hi I'm a little new at CURL, but I'm trying to request some json data and then parse the results. I am having success with retrieving the data, but I can't handle the response. Here's the code
function bitBucketCurl($url)
{
global $bitPassword;
global $bitUsername;
$ch = curl_init();
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERPWD, "$bitUsername:$bitPassword");
curl_setopt($ch, CURLOPT_HEADER, 0);
// grab URL and pass it to the browser
$commitinfo = curl_exec($ch);
// close cURL resource, and free up system resources
curl_close($ch);
return $commitinfo;
}
$json = bitBucketCurl($url);
echo $json; // This seems to work in that, when I load the page, I can see the json data
//turn json data into an array - this is what does not seem to be working
$obj_a = json_decode($json, true);
print_r ($obj_a); //the result is simply a 1 rather than the array I would expect
The basic problem is the json data shows up when I echo $json but when I try to turn that data into an array it doesn't work. When I print the array, I just get a '1'.
I got the required result by adding the following line:
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

sending xml string using php curl but not as post parameter

:)
I'm trying to send an XML using curl but not as post parameter. what I mean is this.
for example.
the receiving side of that XML won't be able to recieve the XML using $_POST variable.
he will need to use the following code:
$xmlStr=null;
$file=fopen('php://input','r');
$xmlStr=fgets($file);
I want to be able to send an xml string using curl via https.
so the following would be wrong:
public static function HttpsNoVerify($url,$postFields=null,$verbose=false) {
// Initialize session and set URL.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
// Set so curl_exec returns the result instead of outputting it.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
if ($postFields !=null) {
curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
}
if ($verbose) {
curl_setopt($ch, CURLOPT_VERBOSE, 1);
}
// Get the response and close the channel.
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
because here i can use HttpsNoVerify($url,array('xml_file'=>'xml..')); and that
will paste it as post parameter. and i want it as post output.
so please I hope i explained myself properly and I explained exactly what I don't want to do.
how can I do what i want to do?
thanks! :)
kfir
Just directly pass the xml string as second parameter instead of an associative array item,
HttpsNoVerify($url, 'xml ..');
This will eventually call
curl_setopt($ch, CURLOPT_POSTFIELDS, "xml ...");
Which will be put in php://input for the remote server.

Results from an cURL request into a form

As mentioned in my previous question I read about cURL and how to work with it. I got the request with the following API: api.openkvk.nl (it's in Dutch, sadly enough) working:
$get = $_POST['bedrijfsnaam'];
$get = str_replace(" ","%20",$get);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://api.openkvk.nl/php/SELECT%20*%20FROM%20kvk%20WHERE%20bedrijfsnaam%20=%20'$get'%20LIMIT%201;");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
print("<pre>"); print_r($result); print("</pre>");
$kvks = $result[0]["RESULT"]["ROWS"][0][2];
echo $kvks;
curl_close($ch);
and I got the results back in the following form:
array(array("RESULT"=>array("TYPES"=>array("bigint","varchar","int","int","varchar","varchar","varchar","varchar","varchar","varchar","bigint","varchar","decimal","decimal","date"),"HEADER"=>array("kvk","bedrijfsnaam","kvks","sub","adres","postcode","plaats","type","status","website","vestiging","rechtsvorm","lat_rad","lon_rad","anbi"),"ROWS"=>array(array("526937320000","Unicmedia","52693732","0","Terschellingstraat 12","1825ND","Alkmaar","Hoofdvestiging",NULL,NULL,"22611126",NULL,NULL,NULL,NULL)))))
What I want to do is the following:
Put this values from the database: kvks, adres, postcode and plaats in a form (so that I can edit them).
I don't know how to do this. Could you give me an explanation?
PS I'm new with API's so I don't understand everything yet.
Update:
Their API is returning it as a php string - change the part of your URL which says /php/ to /json/.
Then, make it so you have $result = json_decode(curl_exec($ch), true);
Now the array access should work.
To get the value of kvks, supposing the value you posted is the in $result, you'd use $kvks = $result[0]["RESULT"]["ROWS"][0][2].
(It looks like you're posting the result of a print_r - try encasing it in <pre> tags when you display it for a much more formatted result)
Since you have PHP getting the values, you could simply output an HTML form with them prefilled:
<form action="savedata.php" method="post">
<?php
echo "<input type='text' name='blah' value=\"" . htmlspecialchars($blah) ."\"><br>";
?>
Then, if $blah is asdf, this would output <input type='text' name='blah' value="asdf">.
When you submit it to your savedata.php method, you'd insert the modified values (now found through $_POST['blah']) into your database however you like.
From my experiments it seems this API is returning PHP code, this would have to be eval'd. eval is a very bad idea.
Can I suggest using the JSON method of the API instead, by replacing the /php/ with /json/
The API will then return a JSON string which you can decode into an object / array
You will also need to add curl_setop($ch, CURLOPT_RETURNTRANSFER,0); to your curl request
Here is some revised code
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://api.openkvk.nl/json/SELECT%20*%20FROM%20kvk%20WHERE%20bedrijfsnaam%20=%20'$get'%20LIMIT%201;");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
$result = curl_exec($ch);
curl_close($ch);
$apiResult = json_decode($result, true);
$apiResult will now contain an array with your result
A var_dump($apiResult) will give you
array
0 =>
array
'RESULT' =>
array
'TYPES' =>
array
...
'HEADER' =>
array
...
'ROWS' =>
array
...
Now that you have the array, you should easily be able to insert it into a DB.

Categories