Remove String Before Json Response Body Php - php

Hi I am using WHMCS Api I am getting a response in json format like this
string 'userhowhigh83{"result":"success","orderid":787,"productids":"785","addonids":"","domainids":"","invoiceid":"766"}' (length=113)
I am getting the response correctly from API but it is also giving me the string 'userhowhigh83' where 'howhigh83' is the username and 'user' is given static but when I decode the json result it gives me null. I checked in on an online json decoder when I remove 'userhowhigh83' it will works fine.How can I remove this before json response body.

If you cannot get the string in better shape from your API, you always can use substring on your string to get rid of "userhowhigh83" :
$string = substr($string , strpos($string , "{"));

This will do as well:
list($username, $jsonData) = explode('{', $json);
echo '{' . $jsonData;
echo $username;
Another approach will be:
preg_match('/{.*?}/', $json, $matches);
echo $matches[0];

Related

Json string conversion to json object

I have been stuck in this issue and cant seem to fix it.. I have this JSON STRING
$unBillableArr = ["{'id' : '123','to' : '+923412268656','MsgReceivedFrom' : '03349433314', 'message':'Qwertyy ', 'recdate':'2017-11-20 19:01:49'}"];
I need to convert it into array of object or maybe just one json object.. I have tried doing
json_decode($unBilledArr , true);
It gives me null.
Already tried these solutions as well
Convert a string to JSON object php
https://jonsuh.com/blog/convert-loop-through-json-php-javascript-arrays-objects/
I must be doing something wrong.. cant seem to figure out what..
P.s : This is the response i am getting and i can not do anything about the response.
You are trying to decode an array, either specify the specific item within the array, or make it a string.
For instance:
$unBillableArr = '{"id":"123", "to":"+923412268656", "MsgReceivedFrom":"03349433314", "message":"Qwertyy", "recdate":"2017-11-20 19:01:49"}';
$json = json_decode($unBillableArr, true);
// Or
$unBillableArr = ['{"id":"123", "to":"+923412268656", "MsgReceivedFrom":"03349433314", "message":"Qwertyy", "recdate":"2017-11-20 19:01:49"}'];
$json = json_decode($unBillableArr[0], true);
However, given the string you are receiving does not contain valid JSON and you are unable to control what you receive, I have prepared the following that will replace the single quotes in your JSON, and decode each item into an array:
$unBillableArr = ["{'id' : '123','to' : '+923412268656','MsgReceivedFrom' : '03349433314', 'message':'Qwertyy ', 'recdate':'2017-11-20 19:01:49'}"];
// Loop through each JSON string
$jsonObjects = []; // Change this name...
foreach ($unBillableArr as $jsonString) {
$jsonObjects[] = json_decode(str_replace("'", '"', $jsonString), true);
}
print_r($jsonObjects); // Proof it works
Please bear in mind that I would consider this to be a dirty fix. To fix this properly, you should go back to the source and ensure that the JSON they are returning to you is valid.

Part of string missing after urldecode() in php

I have an encoded string (it is too long to be posted here). When I use different utilities for decoding the string (http://www.the-art-of-web.com/javascript/escape/) the string looks perfect after urldecode(). However, when I actually pass the string through urldecode() in my php file on my testing environment the first 100 or so characters are missing. I cannot figure out why. I have tried both urldecode and rawurldecode. If you want to see the string I am trying to process you can make a GET request against this url http://pacific-wave-7885.herokuapp.com/api/opencart the string I am working with is the "contents" value of the JSON object
What i am trying to accomplish:
I want to make a php file that calls the above api address, gets the contents from the JSON object, decodes the string and parses the code.
here is what I have tried:
function utf8_urldecode($str) {
$str = preg_replace("/%u([0-9a-f]{3,4})/i","&#x\\1;",urldecode($str));
return html_entity_decode($str,null,'UTF-8');;
}
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Accept-language: en\r\n" .
"Cookie: foo=bar\r\n"
)
);
$context = stream_context_create($opts);
$file = file_get_contents('http://pacific-wave-7885.herokuapp.com/api/opencart', false, $context);
$contents_decode = utf8_urldecode($file);
echo $contents_decode;
You can see with this code that the "contents" starts with "language->load('shipping/usps')" and is missing the first 100 or so characters of that part of the string.
I have also tried this:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://pacific-wave-7885.herokuapp.com/api/opencart");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
$data = json_decode($output, true);
$contents = $data[0]['contents'];
$contents_decode = urldecode($contents);
echo $contents_decode;
curl_close($ch);
This also produces the same result - part of the beginning of the string is missing.
to reiterate: if you grab the encoded string straight from the JSON object and use an online decoding tool the string looks great, but once it is passed through urldecode() in my php file the first part of the string is missing characters.
If anyone can see what I am missing I would be so grateful.
Just fyi: My php environment is the latest version of XAMPP with php5 and the JSON object is coming from a NODE server with express.js.
If anyone has a better idea of how I can pass php code as a string from a Node server to a PHP server and then parse it I would be open to that as well.
I'm going to make two assumptions:
It's showing up starting at language->load('shipping/usps');
You are viewing the returned string in your browser.
Good news is that you aren't missing any characters! The browser is simply misinterpreting the tags -
<?php
class ModelShippingUsps extends Model {
public function getQuote($address) {
$this->
The browser is trying to make sense of it - it doesn't know this is PHP, it thinks it is HTML. It sees < and thinks "oh cool, beginning of an HTML tag." And then it sees ? and it just tries to figure out what kind of malformed tag this is, and then it see's -> and it decides it must be an HTML comment, so it parses it as:
<!--?php
class ModelShippingUsps extends Model {
public function getQuote($address) {
$this--->
Change echo $contents_decode; to echo "<textarea>" . $contents_decode . "</textarea>" and you'll see the full string.
Why not just return the data (instead of a PHP block in the contents) and have your PHP class on the receiving end decode the JSON and complete the logic.
If you are insisting on getting the PHP block back...it might be easier to just return a JSON response from node/express and use json_decode to pull it into an array. In playing with this the only way I could make your PHP block JSON friendly was to escape it then encodeURIComponent.
<?php
$jsonString = '{
"name":"usps.php",
"version":1,
"platform":"opencart",
"contents":"%253C%253Fphp%250Aclass%2520ModelShippingUsps%2520extends...57D%250A%2509%2509%257D%250A%250A%2509%2509return%2520%2524method_data%253B%250A%2509%257D%250A%257D%250A%253F%253E",
"_id":"53c40942bddf820200000007",
"__v":0
}
';
$jsonArr = json_decode( $jsonString, true);
var_dump( urldecode( urldecode( $jsonArr["contents"] ) ) );
?>

Parsing JSON in PHP with a prepend of sorts

if my JSON data is coming back as this:
{"errorCodes":[0]}resultArray=[{....}]
how do I grab the resultArray as the actual JSON string and ignore the rest?
and why would I need errorCodes in front of it?
Just use string manipulation to get rid of everything up through resultArray= and then decode with json_decode().
$json_raw = '...'; // the raw "JSON" string
$delimiter = 'resultArray=';
$cleaned_json = substr($json_raw, strpos($json_raw,$delimiter) + strlen($delimiter)));
$object = json_decode($cleaned_json);

In PHP, How to search and match a specific string with JSON data?

I have a bunch of strings and I want to know if they exist in the JSON response.
I used the following code but it is not working. I do not want to loop through the JSON data.
$url = "https://graph.facebook.com/me/feed?access_token=".$session['access_token'];
$page=file_get_contents($url);
$json_a = json_decode($page,true);
$pos = strpos($page, $mystring);
if($pos == true)
{
do something
}
$page does not contain a string with the contents of the JSON feed. How to convert JSON to string so I can check for $mystring ?
EDIT:
This is strange.
When I use the url https://graph.facebook.com/me/feed?access_token=".$session['access_token']
I get empty data, but when I use "https://graph.facebook.com/me/friends?access_token=".$session['access_token'];
Everything is fine and I get the list of all my friends. I am not able to understand where I am going wrong?
This is the link http://developers.facebook.com/docs/reference/api/
I used the exact url format for Profile feed (Wall): https://graph.facebook.com/me/feed?access_token=...
JSON IS a string, until you run it through the decode function and its gets converted to a php structure. You should be able to do
if (strpos($page, "your search string") !== FALSE) {
echo "hey, it's in there";
}
If your $page is coming out blank, then your file_get_contents call is failing somehow.

PHP json_decode() returns NULL with seemingly valid JSON?

I have this JSON object stored on a plain text file:
{
"MySQL": {
"Server": "(server)",
"Username": "(user)",
"Password": "(pwd)",
"DatabaseName": "(dbname)"
},
"Ftp": {
"Server": "(server)",
"Username": "(user)",
"Password": "(pwd)",
"RootFolder": "(rf)"
},
"BasePath": "../../bin/",
"NotesAppPath": "notas",
"SearchAppPath": "buscar",
"BaseUrl": "http:\/\/montemaiztusitio.com.ar",
"InitialExtensions": [
"nem.mysqlhandler",
"nem.string",
"nem.colour",
"nem.filesystem",
"nem.rss",
"nem.date",
"nem.template",
"nem.media",
"nem.measuring",
"nem.weather",
"nem.currency"
],
"MediaPath": "media",
"MediaGalleriesTable": "journal_media_galleries",
"MediaTable": "journal_media",
"Journal": {
"AllowedAdFileFormats": [
"flv:1",
"jpg:2",
"gif:3",
"png:4",
"swf:5"
],
"AdColumnId": "3",
"RSSLinkFormat": "%DOMAIN%\/notas\/%YEAR%-%MONTH%-%DAY%\/%TITLE%/",
"FrontendLayout": "Flat",
"AdPath": "ad",
"SiteTitle": "Monte Maíz: Tu Sitio",
"GlobalSiteDescription": "Periódico local de Monte Maíz.",
"MoreInfoAt": "Más información aquí, en el Periódico local de Monte Maíz.",
"TemplatePath": "templates",
"WeatherSource": "accuweather:SAM|AR|AR005|MONTE MAIZ",
"WeatherMeasureType": "1",
"CurrencySource": "cotizacion-monedas:Dolar|Euro|Real",
"TimesSingular": "vez",
"TimesPlural": "veces"
}
}
When I try to decode it with json_decode(), it returns NULL. Why?
The file is readable (I tried echoing file_get_contents() and it worked ok).
I've tested JSON against http://jsonlint.com/ and it's perfectly valid.
What's wrong here?
This worked for me
json_decode( preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $json_string), true );
It could be the encoding of the special characters. You could ask json_last_error() to get definite information.
You could try with it.
json_decode(stripslashes($_POST['data']))
If you check the the request in chrome you will see that the JSON is text, so there has been blank code added to the JSON.
You can clear it by using
$k=preg_replace('/\s+/', '',$k);
Then you can use:
json_decode($k)
print_r will then show the array.
Maybe some hidden characters are messing with your json, try this:
$json = utf8_encode($yourString);
$data = json_decode($json);
I had the same problem and I solved it simply by replacing the quote character before decode.
$json = str_replace('"', '"', $json);
$object = json_decode($json);
My JSON value was generated by JSON.stringify function.
For me the php function stripslashes() works when receiving json from javascript. When receiving json from python, the second optional parameter to the json_decode call does the trick since the array is associative. Workes for me like a charm.
$json = stripslashes($json); //add this line if json from javascript
$edit = json_decode($json, true); //adding parameter true if json from python
this help you to understand what is the type of error
<?php
// A valid json string
$json[] = '{"Organization": "PHP Documentation Team"}';
// An invalid json string which will cause an syntax
// error, in this case we used ' instead of " for quotation
$json[] = "{'Organization': 'PHP Documentation Team'}";
foreach ($json as $string) {
echo 'Decoding: ' . $string;
json_decode($string);
switch (json_last_error()) {
case JSON_ERROR_NONE:
echo ' - No errors';
break;
case JSON_ERROR_DEPTH:
echo ' - Maximum stack depth exceeded';
break;
case JSON_ERROR_STATE_MISMATCH:
echo ' - Underflow or the modes mismatch';
break;
case JSON_ERROR_CTRL_CHAR:
echo ' - Unexpected control character found';
break;
case JSON_ERROR_SYNTAX:
echo ' - Syntax error, malformed JSON';
break;
case JSON_ERROR_UTF8:
echo ' - Malformed UTF-8 characters, possibly incorrectly encoded';
break;
default:
echo ' - Unknown error';
break;
}
echo PHP_EOL;
}
?>
This error means that your JSON string is not valid JSON!
Enable throwing exceptions when an error happens and PHP will throw an exception with the reason for why it failed.
Use this:
$json = json_decode($string, null, 512, JSON_THROW_ON_ERROR);
Just thought I'd add this, as I ran into this issue today. If there is any string padding surrounding your JSON string, json_decode will return NULL.
If you're pulling the JSON from a source other than a PHP variable, it would be wise to "trim" it first:
$jsonData = trim($jsonData);
The most important thing to remember, when you get a NULL result from JSON data that is valid is to use the following command:
json_last_error_msg();
Ie.
var_dump(json_last_error_msg());
string(53) "Control character error, possibly incorrectly encoded"
You then fix that with:
$new_json = preg_replace('/[[:cntrl:]]/', '', $json);
Here is how I solved mine https://stackoverflow.com/questions/17219916/64923728 .. The JSON file has to be in UTF-8 Encoding, mine was in UTF-8 with BOM which was adding a weird &65279; to the json string output causing json_decode() to return null
In my case , i was facing the same issue , but it was caused by slashes inside the json string so using
json_decode(stripslashes($YourJsonString))
OR
json_decode( preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $YourJsonString), true );
If the above doesnt work, first replace the quotes from html quote , this might be happening if you are sending data from javascript to php
$YourJsonString = stripslashes($YourJsonString);
$YourJsonString = str_replace('"', '"', $YourJsonString);
$YourJsonString = str_replace('["', '[', $YourJsonString);
$YourJsonString = str_replace('"]', ']', $YourJsonString);
$YourJsonString = str_replace('"{', '{', $YourJsonString);
$YourJsonString = str_replace('}"', '}', $YourJsonString);
$YourJsonObject = json_decode($YourJsonString);
Will solve it,
It's probably BOM, as others have mentioned. You can try this:
// BOM (Byte Order Mark) issue, needs removing to decode
$bom = pack('H*','EFBBBF');
$response = preg_replace("/^$bom/", '', $response);
unset($tmp_bom);
$response = json_decode($response);
This is a known bug with some SDKs, such as Authorize.NET
If you are getting json from database, put
mysqli_set_charset($con, "utf8");
after defining connection link $con
Just save some one time. I spent 3 hours to find out that it was just html encoding problem. Try this
if(get_magic_quotes_gpc()){
$param = stripslashes($row['your column name']);
}else{
$param = $row['your column name'];
}
$param = json_decode(html_entity_decode($param),true);
$json_errors = array(
JSON_ERROR_NONE => 'No error has occurred',
JSON_ERROR_DEPTH => 'The maximum stack depth has been exceeded',
JSON_ERROR_CTRL_CHAR => 'Control character error, possibly incorrectly encoded',
JSON_ERROR_SYNTAX => 'Syntax error',
);
echo 'Last error : ', $json_errors[json_last_error()], PHP_EOL, PHP_EOL;
print_r($param);
So, html_entity_decode() worked for me. Please try this.
$input = file_get_contents("php://input");
$input = html_entity_decode($input);
$event_json = json_decode($input,true);
It took me like an hour to figure it out, but trailing commas (which work in JavaScript) fail in PHP.
This is what fixed it for me:
str_replace([PHP_EOL, ",}"], ["", "}"], $JSON);
I recommend creating a .json file (ex: config.json).
Then paste all of your json object and format it. And thus you will be able to remove all of that things that is breaking your json-object, and get clean copy-paste json-object.
I also face the same issue...
I fix the following steps... 1) I print that variable in browser 2) Validate that variable data by freeformatter 3) copy/refer that data in further processing
after that, I didn't get any issue.
This happen because you use (') insted {") in your value or key.
Here is wrong format.
{'name':'ichsan'}
Thats will be return NULL if you decode them.
You should pass the json request like this.
{"name":"ichsan"}
I've solved this issue by printing the JSON, and then checking the page source (CTRL/CMD + U):
print_r(file_get_contents($url));
Turned out there was a trailing <pre> tag.
you should ensure these points
1. your json string dont have any unknowns characters
2. json string can view from online json viewer (you can search on google as online viewer or parser for json) it should view without any error
3. your string dont have html entities it should be plain text/string
for explanation of point 3
$html_product_sizes_json=htmlentities($html);
$ProductSizesArr = json_decode($html_product_sizes_json,true);
to (remove htmlentities() function )
$html_product_sizes_json=$html;
$ProductSizesArr = json_decode($html_product_sizes_json,true);
For my case, it's because of the single quote in JSON string.
JSON format only accepts double-quotes for keys and string values.
Example:
$jsonString = '{\'hello\': \'PHP\'}'; // valid value should be '{"hello": "PHP"}'
$json = json_decode($jsonString);
print $json; // null
I got this confused because of Javascript syntax. In Javascript, of course, we can do like this:
let json = {
hello: 'PHP' // no quote for key, single quote for string value
}
// OR:
json = {
'hello': 'PHP' // single quote for key and value
}
but later when convert those objects to JSON string:
JSON.stringify(json); // "{"hello":"PHP"}"
Before applying PHP related solutions, validate your JSON format. Maybe that is the problem. Try this online JSON format validator.
For me, I had to turn off the error_reporting, to get json_decode() working correctly. It sounds weird, but true in my case. Because there is some notice printed between the JSON string that I am trying to decode.
I had exactly the same problem
But it was fixed with this code
$zip = file_get_contents($file);
$zip = json_decode(stripslashes($zip), true);
I had the same issue and none of the answers helped me.
One of the variables in my JSON object had the value Andaman & Nicobar. I removed this & and my code worked perfectly.
<?php
$json_url = "http://api.testmagazine.com/test.php?type=menu";
$json = file_get_contents($json_url);
$json=str_replace('},
]',"}
]",$json);
$data = json_decode($json);
echo "<pre>";
print_r($data);
echo "</pre>";
?>

Categories