I’m new to regex and I’m trying to grab the JSON response from a cURL request in PHP.
I was thinking of using preg_match_all.
Edit: Should have mentioned the full response from curl_exec() includes header information which is why I need to extract the JSON.
HTTP/1.1 401 Unauthorized Server: Apache-Coyote/1.1 WWW-Authenticate: Digest realm="", qop="auth", [... etc]
The JSON I want looks something like this (following all headers):
{ "requests" :
[ {
"request_id" : 10298,
"name" : "CURL Test2",
"submitter" : "First Last",
"hide" : false,
"priority" : 10,
"tags" : [ "label 2" ],
"body" :
{ "type" : "html", "content" : "" },
"runs" : 0
} ]
}
Was hoping to just grab everything between the curly braces. However, when I do this it grabs everything from the first opening brace to the first closing brace. For extensibility, I just want to grab everything within and including the first opening brace and the last closing brace.
Technically it could just start at the first opening brace and return everything until end of the response (there’s nothing following the JSON).
Thoughts?
Regex is great, but definitely not the correct tool for this.
There is a function
json_decode()that can handle this for you.It will return the structure as an object. You can return it as an array by setting the second argument to
TRUE. Even if PHP didn’t have this function, you are better off writing or using an existing JSON parser than trying to extract portions with regex.If you are using the headers and need to separate the body into a separate variable, you should do something like the following where
$chis an instance of curl and$resultis the return ofcurl_exec().