I have a json respond that I want to check and return values accordingly:
the Json code is:
{
"success": "true",
"result": "ok"
}
And I need to check the success status and return an array to the controller accordingly.
I was trying to decode and ask questions on the value as follow:
$obj = json_decode($response,true);
if ($obj['success'] =='true')
return array(
'error' => 0,
'msg' => sprintf("successfully")
);
I am not sure what i am doing wrong since I can't get the 0 in the error on array returns.
There is another json code that I need to deal with and it is this:
Negative Response:
{
“success” : “false” ,
“error”:{
“code”:"MANDATORY_FIELDS_MISSING",
"message”: “Phone number is a mandatory field"
}
}
The same goes with this.
I would be happy if you couls assist me with gettin it to work properly.
Thank you.
Arye
Actually your code working fine. You are confused with printing and returning.
Please check this:--
<?php
$response = '{"success": "true","result": "ok"}';
$obj = json_decode($response,true);
if ($obj['success'] =='true')
print_r (array(
'error' => 0,
'msg' => sprintf("successfully")
));
?>
Output:-- http://prntscr.com/729h1o
So i think instead of return you need to print it out.
And you can use var_dump as well as echo <pre/>;print_r(your array inside if) just for look a bit good.
code:
$json = '
{
"success": "true",
"result": "ok"
}';
$obj = json_decode($json, true);
if ($obj['success'] == 'true')
var_dump(array(
'error' => 0,
'msg' => 'successfully'
));
output:
array(2) {
'error' =>
int(0)
'msg' =>
string(12) "successfully"
}
When you run the code above, do you get the same output I see?
Related
I need to create a json response to look like Stripe API response using PHP.
This is the structure I want to get:
{ "body": "{\n \"error\": \"Please enter a valid secret key\",\n}\n", }
This is the code I have so far:
first I create the array:
class Error {
public $errors = array(
'body' => array( 'error' => false ),
);
if ($this->errors['body']['error'] === false) {
$this->errors['body']['error'] = 'Please enter a valid secret key'
}
$resp = json_encode( $this->errors )
echo wp_send_json( $resp );
}
but the result I get is:
json_encode result:
{"body":{"error":"Please enter a valid secret key"}}
echo wp_send_json( $resp ) result:
res = "{\"body\":{\"error\":\"Please enter a valid secret key\"}}"
I don't want the body to be encoded.
What am I missing?
It looks like only the data is json_encoded with the error...
$this->errors['body'] = json_encode(
['error' => 'Please enter a valid secret key']);
This won't have the newlines in it, see if that is a problem.
Or to do this at the end (useful to include that you need this in the question)...
$resp = json_encode( $this->errors['body'], JSON_PRETTY_PRINT );
echo wp_send_json(['data' => $resp]);
I'm trying to decode JSON format
My API Endpoint is https://api.reliableserver.host/api/landings
And this is the output
{
"success": true,
"data": [
{
"id": 1,
"primary_balance": "$4,184.37",
"primary_currency": "USD",
"secondary_balance": "¥0",
"secondary_currency": "JPY",
"tertiary_balance": "฿0.00",
"tertiary_currency": "THB",
"first_language": "ไทย",
"second_language": "English",
"footer_text": "a",
"created_at": "2020-10-26T07:45:49.000000Z",
"updated_at": "2020-10-28T05:31:04.000000Z",
"deleted_at": null
}
],
"message": "Landings retrieved successfully"
}
I need to echo individual values, for example: Primary Balance: $4,184.37
I tried using this:
$url = "https://api.reliableserver.host/api/landings";
$obj = json_decode($url);
echo $obj>primary_balance;
But it didnt work, kindly guide me what am I doing wrong.
You can do this way :
$url = '{"success": true,"data": [{"id": 1,"primary_balance": "$4,184.37","primary_currency": "USD","secondary_balance": "¥0","secondary_currency": "JPY","tertiary_balance": "฿0.00","tertiary_currency": "THB","first_language": "ไทย","second_language": "English","footer_text": "a","created_at": "2020-10-26T07:45:49.000000Z","updated_at": "2020-10-28T05:31:04.000000Z","deleted_at": null}],"message": "Landings retrieved successfully"}';
$obj = json_decode($url, true);
echo $obj['data'][0]['primary_balance'];
// output $4,184.37
Above code tested here
You need file_get_contents() method to get the JSON data from your given URL.
$url = "https://api.reliableserver.host/api/landings";
$obj = json_decode(file_get_contents($url), true);
echo $obj['data'][0]['primary_balance'];
// output $4,184.37
Basically, you are not calling that api anywhere. If it is an open endpoint (without auth or headers, you can do file_get_contents() or I suggest you to use curl.
Also, you need to check on response data structure, it has a 'data' key which is an array. so you need to use foreach to iterate on the 'data' key.
I have given a sample answer that should work if there is only 1 item in data.
$url = "https://api.reliableserver.host/api/landings";
$resp = file_get_contents($url);
$obj= json_decode($resp);// will return in object form
echo $obj->data[0]->primary_balance;
or
$url = "https://api.reliableserver.host/api/landings";
$resp = file_get_contents($url);
$obj= json_decode($resp, true); // will return in array form
echo $obj['data'][0]['primary_balance'];
json_decode()
Hi I get an error of responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.inputDataNilOrZeroLength) I guess this is caused by the amount I passed to my backend server. But, I couldn't find out why. If I process full refund (not using amount and currency), everything works fine.
Below code is in iOS.
print(countOrders)
var requestString = "http://xxxxx.com/fullRefund.php"
var params = ["chargeId": chargeId]
let amountStr = String(Int(sellingPrice * Double(quantity)))
if countOrders > 1 {
requestString = "http://xxxxx.com/partialRefund.php"
params = ["chargeId": chargeId, "amount": amountStr, "currency": currency]
}
print(requestString)
print(chargeId)
print(amountStr)
print(currency)
Alamofire.request(requestString, method: .post, parameters: params).responseJSON { (response) in
switch response.result {
case .success(_):
break
case .failure(let error):
print(error)
break
}
}
Every input should be correct as it prints
2
http://xxxxx.com/partialRefund.php
ch_1BDdTTLYXQrQQLvfRzXnzLsh
4083
CNY
responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.inputDataNilOrZeroLength)
Here is the charge detail from Stripe
ID: ch_1BDdTTLYXQrQQLvfRzXnzLsh
Amount: ¥6,366.00 CNY → $7,391.84 HKD
Below code is partialRefund.php. I guess something wrong in amount since error shows inputDataNilOrZeroLength
<?php
require_once('stripe-php/init.php');
\Stripe\Stripe::setApiKey('sk_test_keyyyyyyyyyyyyyyyy');
$chargeId = $_POST['chargeId'];
$amount = $_POST['amount']; // this line is deleted in fullRefund.php
$currency = $_POST['currency']; // this line is deleted in fullRefund.php
try {
$re = \Stripe\Refund::create(
array(
"charge" => $chargeId,
"amount" => $amount*100, // this line is deleted in fullRefund.php
"currency" => $currency // this line is deleted in fullRefund.php
)
);
$json = array(
'status' => 'Success'
);
echo json_encode($json);
} catch(\Stripe\Error\Card $e) {
$json = array(
'status' => 'Failure',
'message' => $e->getMessage()
);
echo json_encode($json);
}
?>
That looks like you're getting an error in your response to the iOS app, rather than in something coming into your PHP script. You might want to try switching to responseString to see if that fixes it, or try adding a Content-Type header before you echo your JSON:
header('Content-Type: application/json');
The variable $response in the below code is NULL even though it should be the value of the SOAP request. (a list of tides). When I call $client->__getLastResponse() I get the correct output from the SOAP service.
Anybody know what is wrong here? Thanks! :)
Here is my code :
$options = array(
"trace" => true,
"encoding" => "utf-8"
);
$client = new SoapClient("http://opendap.co-ops.nos.noaa.gov/axis/webservices/highlowtidepred/wsdl/HighLowTidePred.wsdl", $options);
$params = array(
"stationId" => 8454000,
"beginDate" => "20060921 00:00",
"endDate" => "20060922 23:59",
"datum" => "MLLW",
"unit" => 0,
"timeZone" => 0
);
try {
$result = $client->getHLPredAndMetadata($params);
echo $client->__getLastResponse();
}
catch (Exception $e) {
$error_xml = $client->__getLastRequest();
echo $error_xml;
echo "\n\n".$e->getMessage();
}
var_dump($result);
The reason that the $result (or the response to the SoapCall) is null is indeed because the WSDL is invalid.
I just ran into the same problem - the WSDL said the response should be PackageChangeBatchResponse yet the actual XML returns has PackageChangeResponse
Changing the WSDL to match the response / changing the response to match the WSDL resolves the issue
you should give an option parameter as below :
<?php
// below $option=array('trace',1);
// correct one is below
$option=array('trace'=>1);
$client=new SoapClient('some.wsdl',$option);
try{
$client->aMethodAtRemote();
}catch(SoapFault $fault){
// <xmp> tag displays xml output in html
echo 'Request : <br/><xmp>',
$client->__getLastRequest(),
'</xmp><br/><br/> Error Message : <br/>',
$fault->getMessage();
}
?>
"trace" parameter enables the output of request. Now, you should see the SOAP request.
(source: PHP.net
My Code
var json = xmlhttp.responseText; //ajax response from my php file
obj = JSON.parse(json);
alert(obj.result);
And in my php code
$result = 'Hello';
echo '{
"result":"$result",
"count":3
}';
The problem is: when I alert obj.result, it shows "$result", instead of showing Hello.
How can I solve this?
The basic problem with your example is that $result is wrapped in single-quotes. So the first solution is to unwrap it, eg:
$result = 'Hello';
echo '{
"result":"'.$result.'",
"count":3
}';
But this is still not "good enough", as it is always possible that $result could contain a " character itself, resulting in, for example, {"result":""","count":3}, which is still invalid json. The solution is to escape the $result before it is inserted into the json.
This is actually very straightforward, using the json_encode() function:
$result = 'Hello';
echo '{
"result":'.json_encode($result).',
"count":3
}';
or, even better, we can have PHP do the entirety of the json encoding itself, by passing in a whole array instead of just $result:
$result = 'Hello';
echo json_encode(array(
'result' => $result,
'count' => 3
));
You should use json_encode to encode the data properly:
$data = array(
"result" => $result,
"count" => 3
);
echo json_encode($data);
You're using single quotes in your echo, therefore no string interpolation is happening
use json_encode()
$arr = array(
"result" => $result,
"count" => 3
);
echo json_encode($arr);
As a bonus, json_encode will properly encode your response!
Try:
$result = 'Hello';
echo '{
"result":"'.$result.'",
"count":3
}';
$result = 'Hello';
$json_array=array(
"result"=>$result,
"count"=>3
)
echo json_encode($json_array);
That's all.