PHP parse_str

Quick example of how to use PHP’s parse_str command.

Here is an example of my data:

$source = "access_token=CAAWhyYsjaWsBAOCwjZCs&expires=5180531";

What I’m trying to do is just grab the string of the access_token variable from the URL. ┬áSo above I’ve dropped it into the $source PHP variable.

Now using parse_str I can get that into an array like so:

$source = "access_token=CAAWhyYsjaWsBAOCwjZCs&expires=5180531";
parse_str($source, $output);

Next I just need to select the section I want, for this example I need the access_token, so my final code is:

<?php
            $source = "access_token=CAAWhyYsjaWsBAOCwjZCs&expires=5180531";
            parse_str($source, $output);
            echo $output['access_token'];?>

If I wanted the expires field I’d modify to this:

<?php
            $source = "access_token=CAAWhyYsjaWsBAOCwjZCs&expires=5180531";
            parse_str($source, $output);
            echo $output['expires'];?>

Output demo

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *