search

Home  >  Q&A  >  body text

Problems encountered when using strpos() PHP function for information retrieval and cropping

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...

P粉692052513P粉692052513431 days ago651

reply all(1)I'll reply

  • P粉598140294

    P粉5981402942023-09-22 00:33:25

    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:

    $data = '{
       "name":"Full Name",
       "DisplayName":"St Philip\u0026#39;",
       "grade":"grade",
       "percentage":10,
       "event":{
          "EventName":"Event Name",
          "maxErrors":10
       }
    }';

    You can then convert the JSON to a normal PHP array and access its keys:

    $decodedData = json_decode ($data, true);
    echo $decodedData['DisplayName'];

    The data result is a URL-encoded string:

    If you need a non-URL encoded string, just add the conversion:

    echo htmlspecialchars_decode($decoded['DisplayName']);

    You will get:

    reply
    0
  • Cancelreply