I am trying to retrieve an array from an API, but every time it is returning an empty array after every attempt.
This is my coding which is fetching data from api:
<?php
$array=array("name"=>"name1");
$url = "http://getsjobs.esy.es/registerapi.php?".http_build_query($array);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$json = curl_exec($ch);
curl_close($ch);
$data = json_decode($json,true);
if (is_array(json_decode($data )) || is_object(json_decode($data)))
{ echo 'array exists'; }
else { echo 'Not an array'; }
?>
this is my api code
<?php
if(isset($_GET['Array'])) {
$array = $_GET['Array'];
header('Content-type: application/json');
}
?>
Even if i use json_encode($array). It is returning empty array. I can receive single value or single array element, but not able to send and receive entire
array from json.
I am not able to find any relevant post. Any link or suggestion will be helpful
My PHP is rusty, but the problem looks to me to be because your API is looking for a parameter called "Array", but nowhere in your calling block does it actually send a GET parameter called "Array".
Your code looks a bit incomplete, so maybe I'm misunderstanding something.
look here: you're decoding it twice.
$data = json_decode($json,true);
if (is_array(json_decode($data )) || is_object(json_decode($data)))
{ echo 'array exists'; }
else { echo 'Not an array'; }
simply:
$data = json_decode($json,true);
if (is_array($data ))
{ echo 'array exists'; }
else { echo 'Not an array'; }
if it still doesn't works, see what echo json_last_error_msg(); returns.
Try to check if your $json is a valid json too. Check if what echo $json; returns is valid here: http://jsonformatter.curiousconcept.com/
Related
Why can't I echo $phone_number in this code? It says
Undefined index: phone_number. but when I echo $response it returns the values
<?php
$ch = curl_init( 'https://mighty-inlet-78383.herokuapp.com/api/hotels/imagedata');
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => TRUE
));
// Send the request
$response = curl_exec($ch);
// Check for errors
if($response === FALSE){
die(curl_error($ch));
echo 'No responce';
}
// Decode the response
$responseData = json_decode($response);
// Print the date from the response
$phone_number = $responseData['phone_number'];
echo $phone_number;
?>
Because these are arrays within arrays you need to go one level deeper to get the data you want. First, make sure you're returning the JSON as an array, using the 'true' attribute:
$responseData = json_decode($response, true);
Then you can get the first phone number (or any phone number by changing the array index):
echo $responseData[0]['phone_number'];
echo $responseData[1]['phone_number'];
You can also loop through the responses:
foreach($responseData AS $response) {
echo $response['phone_number'];
}
My code is:
$requesturl='https://blockchain.info/tx-index/1fda663d2584425f192eae045d3809950883ebe50f2222f98ef7d31f414f3f96?format=json';
$ch=curl_init($requesturl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$cexecute=curl_exec($ch);
curl_close($ch);
$result = json_decode($cexecute,true);
// to get the first i use
echo $result['out'][0]['addr'];
to get the second I use
echo $result['out'][0]['addr'];
Now my requirement is to look through the array using for each but its throwing error:
foreach ($result['out'] as $adressee) {
echo $adressee.'<br>';
}
for($i=0; $i<count($result['out']); $i++) {
echo $result['out'][$i]["addr"].'<br>';
}
Some Sample codes in PHP manual helped me come up with this solution
I want to parse following json for value of
JSON (saved in my.json):
{
"mackoniv":{"entry":"","lastExit":"","userId":"OPENGOVTJOBS","userNick":"mack"},
"johanna":{"entry":"","lastExit":"","userId":"FREEJOBALERT","userNick":"jone"}
}
Code used :
$json = file_get_contents('my.json');
$json_data = json_decode($json,true);
$userToCheck='johanna';
echo 'userId'.$json_data->$userToCheck->userId;
The above code gives error "Trying to get property of non-object", which i understand as $userToCheck isnt an object of $json_data but how do i access the data of "mackoniv" or even "johanna" when userToCheck part is not to be hardcoded.
If i try following way, it gives same error.
echo 'userId'.$json_data[$userToCheck]['userId'];
first of all json_decode($jsondata, true); would return an array. try to var_dump your $json to make sure you've got the file and then var_dump $json_data.
If you write it like below it should work.
$json = file_get_contents('my.json');
$json_data = json_decode($json, true);
$userToCheck = 'johanna';
echo 'userId = ' . $json_data[$userToCheck]['userId'];
Basically change the line:
echo 'userId' . $json_data->$userToCheck->userId;
with:
echo 'userId = ' . $json_data[$userToCheck]['userId'];
if json_decode second paramether is true, it returns an array, if it is false (default), returns an object. So, if you want to use it as an object, just decode it like: $json_data = json_decode($json);. If this doesn't work, check what echo json_last_error_msg(); returns. If it returns "No error", then the problem is that your file_get_contents() is not refering to the correct file.
I'm trying to understand how to record the result of a curl GET request using php. I'm looking at outputing part or all of the result to mysql.
https://github.com/cloudtrax/docs/blob/master/api/code/php/simple_api_server_test_harness.php
function invoke_curl($method, $endpoint, $headers, $json) {
$api_server = 'https://api.cloudtrax.com';
try {
// get a curl handle then go to town on it
$ch = curl_init($api_server . $endpoint);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
if ($result == FALSE) {
if (curl_errno($ch) == 0)
echo "#### NOTE ####: nil HTTP return: This API call appears to be broken" . "\n";
else
throw new Exception(curl_error($ch), curl_errno($ch));
}
else
echo "RESULT: \n" . $result . "\n";
}
The $result shows like this:
{
"clients": {
"ssid2": 4,
"ssid1": 10
},
"rows": [
{
"time": "2016-03-23T02:45:00Z",
"ssid2": {
"traffic": {
"unclassified": {
// etc...
How can I associate each part of the result too a variable so I can then input too mysql?
It looks like this result in json format. You can use json_decode to decode it:
$resultObject = json_decode($result);
$clients = $resultObject->clients;
// ... get other data from result
The code below will convert the json into a PHP array. You can then use the indexes of the array to pull out values.
$result = json_decode($result);
$clients = $result->clients;
// Some MySQL queries
If your response is a JSON response then you can simply use php's json_decode to get parsed object.
$result = curl_exec($ch);
//to get associative array passing true
$jsonObj = json_decode($result, true);
$clients = $jsonObj['clients'];
$rows = $jsonObj['rows'];
You can refer to these answers for more detail:
Parsing JSON object in PHP using json_decode and
Parsing JSON file with PHP
I know it's basic, but I couldn't get what's wrong because it's not my area.
I am sending some request to a server and print the response like this:
$rest = curl_init();
curl_setopt($rest,CURLOPT_URL,$url);
curl_setopt($rest,CURLOPT_GET,1);
curl_setopt($rest,CURLOPT_HTTPHEADER,$headers);
curl_setopt($rest,CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($rest,CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($rest);
$json = json_decode($response, true);
echo $response;
Where I get this:
{"results":[{"Devices":["52401E7E-C5D7","AE80C0F8-999E","764BFD92-9753","78A23379-2C14","EEA03545-5EB9","E18DDFEC-C3C9"],"UserID":"433011AC-228A-4931-8700-4D050FA18FC1","createdAt":"2015-11-04T15:06:33.564Z","objectId":"3os7BGxRoG","updatedAt":"2015-11-04T17:08:57.635Z"}]}
Then, I am trying to print the JSON or its fields, but I then get nothing:
echo $json;
echo $json['UserID'];
echo $json['Devices'];
To clarify the comments a bit:
$str = '{"results":[{"Devices":["52401E7E-C5D7","AE80C0F8-999E","764BFD92-9753","78A23379-2C14","EEA03545-5EB9","E18DDFEC-C3C9"],"UserID":"433011AC-228A-4931-8700-4D050FA18FC1","createdAt":"2015-11-04T15:06:33.564Z","objectId":"3os7BGxRoG","updatedAt":"2015-11-04T17:08:57.635Z"}]}';
$json = json_decode($str, true); // to an associative array
// to echo the UserID
echo "userID : " . $json['results'][0]['UserID'];
// output: userID : 433011AC-228A-4931-8700-4D050FA18FC1
// to get the structure of the json array in general use print_r() as AbraCadaver pointed out
print_r($json);
In your attempt you were missing the results[0] part.