The site I am working on is using a .net Soap web service for getting data. The initial call returns XML that contains a base64 encoded string. I am able to isolate that string by using $lastResponse = $client->__getLastResponse(); When I use var_dump on the $last response variable I get some thing like
string(10139) "77u/PD94bWwgdmV...=="
When I use echo I get 77u/PD94bWwgdmV...== without the string(10139) to start. I have tried to place the $lastResponse variable into the base64_decode function but it returns nothing at all, not even NULL. I have also tried to split the string first to remove the 77u/ from the start and that does not work at all.
$lastResponse = $client->__getLastResponse();
$splitResponse = preg_split("#/#", $lastResponse);
echo base64_decode($lastResponse);
echo base64_decode($splitResponse[1]);
var_dump($splitResponse[1]);
var_dump(base64_decode($splitResponse[1]));
echo $lastResponse;
The code above returns this to the browser:
string(0) "" string(0) "" 77u/PD94bWwgdmVyc2lvbj0....
But when I copy/paste everything after the 77u/ into an only decoder I get the decoded xml that I am supposed to have returned to me. I am very confused as to what I am missing here any help will be greatly appreciated.
Related
My API URL Returned code in browser as shown below. but json_decode($api_url,true); returns null.
i checked json_last_error();, it returns 4(json error syntax).
it worked with json_decode(file_get_contents($api_url),true);
why it isn't work with json_decode. please help
{"dataset":{"id":27153572,"dataset_code":"20MICRONS_A_DEBT","database_code":"DEB","name":"20 Microns Limited,Total Debt","description":"\u003cp\u003e20 Microns Limited(NSE:20MICRONS)-Total Debt(Annual)\u003c/p\u003e","refreshed_at":"2018-09-21T08:04:08.278Z","newest_available_date":"2018-03-31","oldest_available_date":"2005-03-31","column_names":["PERIOD","STANDALONE","CONSOLIDATED"],"frequency":"annual","type":"Time Series","premium":true,"limit":null,"transform":null,"column_index":null,"start_date":"2005-03-31","end_date":"2018-03-31","data":[["2018-03-31",128.56,133.68],["2017-03-31",144.9,151.73],["2016-03-31",155.18,163.41],["2015-03-31",152.8,164.62],["2014-03-31",162.01,176.64],["2013-03-31",148.49,164.73],["2012-03-31",144.67,158.6],["2011-03-31",81.42,120.31],["2010-03-31",84.35,87.35],["2009-03-31",58.62,58.62],["2008-03-31",46.52,null],["2007-03-31",42.46,null],["2006-03-31",40.03,null],["2005-03-31",38.98,null]],"collapse":null,"order":null,"database_id":14992}}
What you are trying to do has no sense. $api_url is just an url so when you try to decode it then it doesn't have a json stucture and it will throw an exeption.
What you should decode is the data that this url returns to you.
So First you should get data from url then use json_decode($api_url,true);.
To get data you can use file_get_contents or curl.
Props to u_mulder who hit the nail on the head but I want to break this down for you a little.
Purpose of file_get_contents():
The file_get_contents() function is an inbuilt function in PHP which is used to read the contents of a file into a string.
Please note that the 'file' can be a file residing on your web server or a remote file (URL), which in essence will give you a web document back.
Purpose of json_decode():
The json_decode() function is an inbuilt function in PHP which is used to decode a JSON string. It converts a JSON encoded string into a PHP variable.
With that in mind you can see that performing json_decode on an invalid JSON string or a URL will render your result as NULL.
json_decode('https://www.website.com')
This is essentially what you are doing. performing the file_get_contents inside your json_decode first converts your URL/File ('https://www.website.com') into a string, that string then having JSON is then converted into an array by json_decode.
I am trying to pass JSON object from angular to php like this :
<?php
$placeBean = "{{masterCtrl.getLastplace();}}";
//VAR DUMP IS -> string(30) "{"id":1841,"name":"Milano","areaCode":"MI","latitude":0,"longitude":0}"
$json = '{"id":1841,"name":"Milano","areaCode":"MI","latitude":0,"longitude":0}';
//VAR DUMP IS -> string(70) "{"id":1841,"name":"Milano","areaCode":"MI","latitude":0,"longitude":0}"
?>
Then I need to parse the json in $placeBean, because it is not yet a json in php, so I use
<?php
$manage = json_decode($placeBean);
?>
And this is the problem... because it doesn't work, in fact the result is an empty value: instead, if I do the same thing with $json( instead of $placeBean), the code works perfectly.
I Think the issue is some
missing chars, which are placed in$json, and not in $placeBean.
Those are the echo of the variables
ECHO OF JSON ->{"id":1841,"name":"Milano","areaCode":"MI","latitude":0,"longitude":0}
ECHO OF placeBean ->
placeBean{"id":1841,"name":"Milano","areaCode":"MI","latitude":0,"longitude":0}
I Also tried to use json_last_error, which gave me this : - Syntax error, malformed
Well, the first one is not a valid JSON object, for this PHP refuses to parse it.
When you run it though AngularJS it will actually use its own mechanism and replaces the string with the data returned by the masterCtrl.getLastplace() call.
So I'm quite new to programming, and I have nothing else to describe it but a live script, so please correct me with the official term. Anyway, a while ago, I made this bot in php and ran it locally in my browser using xampp on my mac. I could very easily use echo and print_r to print arrays and whatever to the webpage. The script would only run if I reloaded the page, so this is what i'm talking about as 'not live'. Now I have started trying to make a messenger bot in PHP, and i'm using cloud9. I also see the script in a browser, but here, I can only see products of echo and print if they are simple strings I have entered, for example:
print_r("stack overflow is life");
This will print as expected in my browser. However, this is where me talking about 'live' script runs comes into play. Instead of reloading the page, it runs live. The messenger bot will always be active on the server, and it instantly replies to a message sent to it as wanted. I use this code:
/* receive and send messages */
$input = json_decode(file_get_contents('php://input'), true);
file_put_contents("fb.txt", file_get_contents('php://input'));
echo ("<pre>"); print_r($input);
echo ("</pre>");
Now, in this case, the $input is not printed. I see nothing. Now I don't know if this is to do with live server response, or what, but I need to know how to see this is the browser. And I have tested to see if there actually is a successfully converted JSON to array, because I am able to use the info in $input to reply to my facebook messaged and the bot works. I can also output the JSON to a txt file, and see it there, but there is no <pre> tags so it is hard to read, and I want the nice clean array to see in the browser. All code revolves around this, so it is very important.
So you are writing the raw input to the file and json decoding it separately. So it is quite possible you are not actually getting valid json.
If you do pass invalid json, json_decode returns NULL which is why you see that when you var_dump - so you have to call json_last_error to be sure it worked.
From Docs:
http://php.net/manual/en/function.json-decode.php
Returns the value encoded in json in appropriate PHP type. Values true, false and null are returned as TRUE, FALSE and NULL respectively. NULL is returned if the json cannot be decoded or if the encoded data is deeper than the recursion limit.
You should really check if json_decode works, here is an example to demonstrate:
<?php
$badjson = '{bad:"json"}';
$decoded = json_decode($badjson);
if(json_last_error()!==JSON_ERROR_NONE){
echo "Json Decode Failed: ".json_last_error_msg();
}else{
var_dump($decoded);
}
echo "\n---\n";
$goodjson = '{"property":"value"}';
$decoded = json_decode($goodjson);
if(json_last_error()!==JSON_ERROR_NONE){
echo "Json Decode Failed: ".json_last_error_msg();
}else{
var_dump($decoded);
}
See it in action here: http://sandbox.onlinephpfunctions.com/code/3a07e57f4cd01bd63d2945d5e367bbb0a6158195
See PHP Docs: http://php.net/manual/en/function.json-last-error.php
You can use a syntax checker to find the problem with your json e.g. http://jsonlint.com/
A common issue if the json is manually created is failing to wrap properties in double quotes e.g. {property:"value"} is invalid while {"property":"value"} is valid.
Note the reason you have to check json_last_error, and can't rely on NULL meaning it failed is because json_decode('NULL'); would return NULL and that would be correct.
Not sure what is cloud9.
For debug you can try var_dump() function. It will print onto your browser data type and data values, because there could be different type of "nothing". It's not a better way for debugging but a naive one. For better: check debug and breakpoint possibilities in this cloud9.
var_dump() can eat as many arguments as you like, so it's handy to dump everything with php input too to check what comes and how it changes.
I try to create a script that decoding a simple JSON string in PHP and I get the following error:
quoted object property name expected
The string I try to decode is the following :
{"values":[{"url":"http://www.google.com","matches":"http|www|google|com"},{"url":"http://www.yahoo.com","matches":"http|www|yahoo|com"}]}
and the code I use to decoded is the following:
json_decode( $json_string );
I also have try to validate my json string in some online json validators, and the string seems to be fine.
Can someone please help me ?
Do you think the problem exists because of the double quotes ?
Update #1
Definetelly was a debuging issue. I place my experience here just to help other devs may come accross the same issue in the feature:
The problem was that my variable that came with the json string was html encoded so instead of the following string :
{"values":[{"url":"http://www.google.com","matches":"http|www|google|com"},{"url":"http://www.yahoo.com","matches":"http|www|yahoo|com"}]}
my variable came with the following string inside :
{"values":[{"url":"http://www.google.com","matches":"http|www|google|com"},{"url":"http://www.yahoo.com","matches":"http|www|yahoo|com"}]}
The mistake by my side was that I used the print_r method instead of the var_dump . This had as a result to print out the " as " in my page .
The json string is valid, and it works. You can add true for the second parameter of json_decode, and you get back an array.
Try the following:
$json_string = '{"values":[{"url":"http://www.google.com","matches":"http|www|google|com"},{"url":"http://www.yahoo.com","matches":"http|www|yahoo|com"}]}';
var_dump(json_decode($json_string, true));
It works for me.
I want to pass a JSON: {"name":"jason","age":"20} in PHP though POST
In RoR, I can get the two values by using params["name"] & params["age"]
But I don't know how to get them in PHP.
I understand that I can 'translate' the JSON string into associative array by using json_decode but I don't know how to get the JSON string.
In my PHP code, I has tried something like this:
<?php
$json_string = $_POST['params'];
$json_object= json_decode($json_string);
print_r($json_object);
echo $json_object->name;
echo " ";
echo $json_object->age;
?>
Then I has tested the PHP with terminal and I got the correct result
curl -d 'params={"name":"jason", "age":"20"}' xxxx/test_json_decode.php
It works but it seems strange to me, because I didn't set the 'Content-Type: application/json'
Is it the correct way to parse JSON in PHP?
The content-type is only useful in certain cases, such as jquery doing a standard .post where you haven't explicitly told it to expect a json response. A json string is just text, and the content-type is just a clue to the receiver. but you could still send a json string with image/jpeg and still decode it and get a native structure again.
As long as what you pass into json_decode() is a valid JSON string, regardless of the mime-type it was sent with, it'll be decoded into a native structure.