I'm getting raw data from an API that contains a JSON and I'm trying to crop out the JSON-only part from the returned data. I used PHP's strpos() function to write a function to trim the JSON from the beginning (the position of the opening brace) to the end (the position of the closing brace).
But I encountered a problem, some values of the data also contain special characters, including semicolons, which prevents the function from fully cropping...
Is there a better way to solve this problem?
Some examples of data:
$data = { "name" : "Full Name", "DisplayName":"St Philip\u0026#39;", "grade" : "grade", "percentage" : 10, {"EventName":"Event Name","maxErrors":10} };
This is the function I wrote:
function copyData($data, $param1, $param2) { $start = strpos($data, $param1) + strlen($param1); $end = strpos($data, $param2, $start); $return = substr($data, $start, $end - $start); return $return; }
So, using this function, it always stops at DisplayName...
Your $data appears to be a malformed JSON string.
If this is due to bad input, and $data is a normal JSON string, then I recommend changing your strategy.
Assuming the correct JSON string is:
You can then convert the JSON to a normal PHP array and access its keys:
The data result is a URL-encoded string:
If you need a non-URL encoded string, just add the conversion:
You will get: