Can not access Json Array Response - php

Hey im having an issue with an API im trying to integrate...
I have this code:
$deleteOld = $facepp->execute('/person/delete', array('person_name' => $id));
$response = $facepp->execute('/person/create', array('person_name' => $id));
print_r($response);
echo $response['body']['person_id'];
the print_r output is
Array
(
[http_code] => 200
[request_url] => http://apius.faceplusplus.com//person/create
[body] => {
"added_face": 0,
"added_group": 0,
"person_id": "00c812cbd9c763a6dae36a48bc54b855",
"person_name": "3824",
"tag": ""
}
)
I want to return the person_id, but all i get is "{"
SOLUTION:
$response = $facepp->execute('/person/create', array('person_name' => $id));
print_r($response);
$response = json_decode($response['body'], true);
echo $response['person_id'];

You have to user json_decode() function then it will converted into array
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));

SOLUTION:
$response = $facepp->execute('/person/create', array('person_name' => $id));
print_r($response);
$response = json_decode($response['body'], true);
echo $response['person_id'];

Related

Post data using php

I made a API to fetch and store data, I can fetch data without problem, but everything changes when I try to store data, when I send the data it returns [{"success":"0"}]. In the beginning it worked well, used accepted to store data, but suddenly everything changed. I've tried everything, compare the new with the old, changed the code, tables, but even so it always returns [{"success":"0"}] after comparing both (old and new) code I couldn't see much difference. What could I be doing wrong?
Insert data:
function insertloin()
{
if(isset($_POST["loincode"]))
{
$form_data = array(
':loincode' => $_POST["loincode"],
':code' => $_POST["code"],
':specie' => $_POST["specie"],
':grade' => $_POST["grade"],
':vesselname' => $_POST["vesselname"],
':type' => $_POST["type"],
':productformat' => $_POST["productformat"],
':dateprocessed' => $_POST["dateprocessed"],
':datebb' => $_POST["datebb"],
':projectcode' => $_POST["projectcode"],
':netweight' => $_POST["netweight"],
':producttype' => $_POST["producttype"],
':oldoc' => $_POST["oldoc"]
);
$query = "
INSERT INTO loins
(loincode, code, specie, grade, vesselname, type, productformat, dateprocessed, datebb, projectcode, netweight, producttype, oldoc) VALUES
(:loincode, :code, :specie, :grade, :vesselname, :type, :productformat, :dateprocessed, :datebb, :projectcode, :netweight, :producttype, :oldoc)
";
$statement = $this->connect->prepare($query);
if($statement->execute($form_data))
{
$data[] = array(
'success' => '1'
);
}
else
{
$data[] = array(
'success' => '0'
);
}
}
else
{
$data[] = array(
'success' => '0'
);
}
return $data;
}
Test:
if($_GET["action"] == 'insertloin')
{
$data = $api_object->insertloin();
}
Action:
if(isset($_POST["action"]))
{
if($_POST["action"] == 'insertloin')
{
$form_data = array(
'loincode' => $_POST["loincode"],
'code' => $_POST["code"],
'specie' => $_POST["specie"],
'grade' => $_POST["grade"],
'vesselname' => $_POST["vesselname"],
'type' => $_POST["type"],
'productformat' => $_POST["productformat"],
'dateprocessed' => $_POST["dateprocessed"],
'datebb' => $_POST["datebb"],
'projectcode' => $_POST["projectcode"],
'netweight' => $_POST["netweight"],
'producttype' => $_POST["producttype"],
'oldoc' => $_POST["oldoc"]
);
$api_url = "http://192.168.85.160/API/v2/api/test_api.php?action=insertloin";
$client = curl_init($api_url);
curl_setopt($client, CURLOPT_POST, true);
curl_setopt($client, CURLOPT_POSTFIELDS, $form_data);
curl_setopt($client, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($client);
curl_close($client);
$result = json_decode($response, true);
foreach($result as $keys => $values)
{
if($result[$keys]['success'] == '1')
{
echo 'insert';
}
else
{
echo 'error';
}
}
}
Please, help me find the bug.
Kind regards,
Abd
When $statement->execute() returns a false value it means your SQL had some sort of error. But you ignore that false value and instead return the same success status in both your if and your else clause.
To see your error codes try something like this:
if($statement->execute($form_data))
{
$data[] = array(
'success' => '1'
);
}
else
{
echo $statement->errorInfo();
print_r ( $statement->errorInfo() );
die(1);
}
You'll need to look at the error codes you get to see what's wrong and then do something smarter than echo / print_r / die.

PHP Array to Json Object

I need to convert a PHP array to JSON but I don't get what I expect.
I want it to be an object that I can navigate easily with a numeric index.
Here's an example code:
$json = array();
$ip = "192.168.0.1";
$port = "2016";
array_push($json, ["ip" => $ip, "port" => $port]);
$json = json_encode($json, JSON_PRETTY_PRINT);
// ----- json_decode($json)["ip"] should be "192.168.0.1" ----
echo $json;
This is what I get
[
[
"ip" => "192.168.0.1",
"port" => "2016"
]
]
But I want to get an object instead of array:
{
"0": {
"ip": "192.168.0.1",
"port": "2016"
}
}
You want to json_encode($json, JSON_FORCE_OBJECT).
The JSON_FORCE_OBJECT flag, as the name implies, forces the json output to be an object, even when it otherwise would normally be represented as an array.
You can also eliminate the use of array_push for some slightly cleaner code:
$json[] = ['ip' => $ip, 'port' => $port];
just use only
$response=array();
$response["0"]=array("ip" => "192.168.0.1",
"port" => "2016");
$json=json_encode($response,JSON_FORCE_OBJECT);
Just in case if you want to access your objectivitized json whole data OR a specific key value:
PHP SIDE
$json = json_encode($yourdata, JSON_FORCE_OBJECT);
JS SIDE
var json = <?=$json?>;
console.log(json); // {ip:"192.168.0.1", port:"2016"}
console.log(json['ip']); // 192.168.0.1
console.log(json['port']); // 2016
To get array with objects you can create stdClass() instead of array for inner items like below;
<?PHP
$json = array();
$itemObject = new stdClass();
$itemObject->ip = "192.168.0.1";
$itemObject->port = 2016;
array_push($json, $itemObject);
$json = json_encode($json, JSON_PRETTY_PRINT);
echo $json;
?>
A working example http://ideone.com/1QUOm6
In order to get an object and not just a json string try:
$json = json_decode(json_encode($yourArray));
If you want to jsonise the nested arrays as well do:
$json =json_decode(json_encode($yourArray, JSON_FORCE_OBJECT));
$ip = "192.168.0.1";
$port = "2016";
$json = array("response" => array("ip" => $ip, "port" => $port));
//IF U NEED AS JSON OBJECT
$json = [array("ip" => $ip, "port" => $port)]; //IF U NEED AS JSON ARRAY
$json = json_encode($json);
echo $json;

Getting a php array

I need to interpret the array received from a remote licensing.
I am calling the remote api via curl and the answer in the browser is:
The parsed answer from curl done by using:
parse_str(curl_exec($ch), $parsed);
print_r($parsed);
is exactly as here:
Array ( [{"success":true,"uses":154,"purchase":{"id":"GYFt6sW7hbURSVdSpipb5g] => =","created_at":"2015-06-06T16:44:41Z","email":"askolon11#gmail.com","full_name":"daniel","variants":"","custom_fields":[],"product_name":"Direkt 1.2","subscription_cancelled_at":null,"subscription_failed_at":null}} )
I tried already for several hours to get the "success" item so later on to check it if it is true or false.
I used
while (list($var, $val) = each($parsed)) {
print "$var is $val\n";
}
but the result is the same.
Also I tried:
$parsed[0]['success'] or $parsed[0]['success']
and no result as well.
My full code is:
<?php $ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.gumroad.com/v2/licenses/verify");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, true);
$data = array( 'product_permalink' => 'skQsA', 'license_key' => 'AB26AD9D-1B3B42E0-92356540-CF4E7C1B' );
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$output = curl_exec($ch);
$info = curl_getinfo($ch);
$output = array();
parse_str(curl_exec($ch), $parsed);
print_r($parsed); // HERE WE HAVE THE ARRAY
while (list($var, $val) = each($parsed)) {
// print "$var is $val\n";
}
curl_close($ch);
?>
Thank you.
The API seems to return a JSON encoded string. So instead of:
parse_str(curl_exec($ch), $parsed);
use:
$parsed = json_decode(curl_exec($ch), true);
Then a print_r($parsed) will output:
Array
(
[success] => 1
[uses] => 154
...
)
And for checking success value:
if ($parsed['success']) {
// Do stuff
}
Instead of doing
$parsed[0]['success'];
try just
$parsed['success'];
If the array you are getting back is an associative array, then the 'key' will be the word 'success'.
$parsed = [
"success" => true,
"uses" => 154,
"purchase" =>
[
"id" => "GYFt6sW7hbURSVdSpipb5g] => =",
"created_at" => "2015-06-06T16:44:41Z",
"email" => "askolon11#gmail.com",
"full_name" => "daniel",
"variants" => "",
"custom_fields" => [],
"product_name" => "Direkt 1.2",
"subscription_cancelled_at" => null,
"subscription_failed_at" => null
]];
if($parsed['success'])
echo 'true';
else
echo 'false';

How to add json_encode array into json_encode object?

How to add json_encode array into json_encode object ? or other way to make below result?
php result response to jquery ajax
{”a_obj”:”a_obj”,“b_obj_json”:[
{“b_arr1”:b_arr1,“b_arr1-2”:“b_arr1-2”},
{“b_arr2”:b_arr2,“b_arr2-2”:”b_arr2-2”},
... from db push
]
}
:
$response_array = array('a_array'=>'a_array');
$response_array_object = json_encode($response_array, JSON_FORCE_OBJECT);
$b_arr =array(
'b_arr1'=>'b_arr1',
);
json_encode($b_arr);
$response_array_object->append($b_arr);
echo $response_array_object;
Convert JSON to Array with 'json_decode' then use 'array_append' to add new data then 'json_encode' it again.
<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
$array = (array) json_decode($json);
$append = array(
'username' => array('alias' => 'somename', 'realname' => 'stacky');
'password' => 'somepass';
);
$combined = array_merge($array, $append);
$encoded = json_encode($combined);
print_r($encoded);
?>

Customize array from cURL XML response

I need to output an array with a specif format from a cURL request. I tried many ways to format the XML result as needed without luck.
Here's the PHP code
<?php
$request_url = "http://ws.correios.com.br/calculador/CalcPrecoPrazo.aspx?nCdEmpresa=&sDsSenha=&sCepOrigem=71939360&sCepDestino=72151613&nVlPeso=1&nCdFormato=1&nVlComprimento=16&nVlAltura=5&nVlLargura=15&sCdMaoPropria=s&nVlValorDeclarado=200&sCdAvisoRecebimento=n&nCdServico=41106%2C40045&nVlDiametro=0&StrRetorno=xml 4110616,9034,000,001,50SN04004519,2014,000,002,00SS0";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $request_url);
curl_setopt($curl, CURLOPT_TIMEOUT, 130);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($curl);
curl_close($curl);
print_r($response);
?>
It prints the following XML
<servicos>
<cservico>
<codigo>41106</codigo>
<valor>16,90</valor>
<prazoentrega>3</prazoentrega>
...
<erro>0</erro>
<msgerro>
</msgerro>
</cservico>
<cservico>
<codigo>40045</codigo>
<valor>19,20</valor>
<prazoentrega>1</prazoentrega>
...
<erro>0</erro>
<msgerro>
</msgerro>
</cservico>
</servicos>
Or the following array if I apply $xml = new SimpleXMLElement($response);
SimpleXMLElement Object
(
[cServico] => Array
(
[0] => SimpleXMLElement Object
(
[Codigo] => 41106
[Valor] => 16,90
[PrazoEntrega] => 3
...
[Erro] => 0
[MsgErro] => SimpleXMLElement Object
(
)
)
[1] => SimpleXMLElement Object
(
[Codigo] => 40045
[Valor] => 19,20
[PrazoEntrega] => 1
...
[Erro] => 0
[MsgErro] => SimpleXMLElement Object
(
)
)
)
)
What I need to return is and Array like this. I tried almost every method found in other questions here but never got a good way to construct this two-dimension array.
array(
'Option Name' => array(
'id'=>'40045',
'quote'=>'20,20',
'days'=>'1',
),
'Option Name' => array(
'id'=>'40215',
'quote'=>'29,27',
'days'=>'3',
)
)
*Option Name will be retrieved afterwards by ID code.
This should work flawlessly!
$xml = simplexml_load_string($response);
$json = json_encode($xml);
$arr = json_decode($json,true);
$temp = array();
foreach($arr as $k=>$v) {
foreach($v as $k1=>$v1) {
$temp[$k][$k1] = $v1;
}
}
echo "<pre>";print_r($temp);echo "</pre>";
http://ka.lpe.sh/2012/07/26/php-convert-xml-to-json-to-array-in-an-easy-way/
Try this function (pass the response to it and it should return you your array) :
function getArrayFromResponse($response) {
$xml = new SimpleXMLElement($response);
$array = array();
foreach($xml->cServico as $node){
$array[] = array(
'id' => $node->Codigo,
'quote' => $node->Valor,
'days' => $node->PrazoEntrega
);
}
return $array;
}
$ch = curl_init();
$sendurl = "http://example.com";
curl_setopt($ch, CURLOPT_URL, $sendurl);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
curl_close($ch);
$response = preg_replace("/(<\/?)(\w+):([^>]*>)/", "$1$2$3", $data);
$xml = new \SimpleXMLElement($response);
$array = json_decode(json_encode((array)$xml), TRUE);
echo "<pre>";
print_r($array);
Working charming for me.
I finally got it. After testing all your suggestions and many others found on google, I came up with this:
<?php
$request_url = "http://ws.correios.com.br/calculador/CalcPrecoPrazo.aspx?nCdEmpresa=&sDsSenha=&sCepOrigem=71939360&sCepDestino=72151613&nVlPeso=1&nCdFormato=1&nVlComprimento=16&nVlAltura=5&nVlLargura=15&sCdMaoPropria=s&nVlValorDeclarado=200&sCdAvisoRecebimento=n&nCdServico=41106%2C40045&nVlDiametro=0&StrRetorno=xml 4110616,9034,000,001,50SN04004519,2014,000,002,00SS0";
//Setup cURL Request
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $request_url);
curl_setopt($curl, CURLOPT_TIMEOUT, 130);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($curl);
curl_close($curl);
$xml = simplexml_load_string($response);
$services = $xml->cServico;
$result = array();
foreach($services as $service) {
$id = $service->Codigo->__toString();
$quote = $service->Valor->__toString();
$delivery_days = $service->PrazoEntrega->__toString();
//Get simplified service name (option_name)
switch ($id) {
case "40010":
case "40096":
case "40436":
case "40444":
case "40568":
case "40606":
$option_name = 'SEDEX'; break;
case "81019":
case "81868":
case "81833":
case "81850":
$option_name = 'e-SEDEX'; break;
case "41106":
case "41068":
$option_name = 'PAC'; break;
case "40045":
case "40126":
$option_name = 'SEDEX a Cobrar'; break;
case "40215":
$option_name = 'SEDEX 10'; break;
case "40290":
$option_name = 'SEDEX Hoje'; break;
case "81027":
$option_name = 'e-SEDEX Prioritário'; break;
case "81035":
$option_name = 'e-SEDEX Express'; break;
}
$result[$option_name] = array('id' => $id, 'quote' => $quote, 'delivery_days' => $delivery_days);
}
?>
The final secret was to add __toString() to convert values returned as array to a simple string. It prints perfectly. Thank you guys!!
Array
(
[PAC] => Array
(
[id] => 41106
[quote] => 16,90
[delivery_days] => 3
)
[SEDEX a Cobrar] => Array
(
[id] => 40045
[quote] => 19,20
[delivery_days] => 1
)
)

Categories