从cURL结果中提取JSON

时间:2011-06-07 00:17:56

标签: php regex json curl preg-replace

我是regex的新手,我正试图从PHP中的cURL请求中获取JSON响应。

我在考虑使用preg_match_all。

编辑:应该提到curl_exec()的完整响应包含标题信息,这就是我需要提取JSON的原因。

HTTP/1.1 401 Unauthorized Server: Apache-Coyote/1.1 WWW-Authenticate:  Digest realm="",  qop="auth", [... etc]

我想要的JSON看起来像这样(跟随所有标题):

{  "requests" :  
  [ { 
     "request_id" : 10298, 
     "name" : "CURL Test2",  
     "submitter" : "First Last",  
     "hide" : false,  
     "priority" : 10,  
     "tags" : [ "label 2" ],  
     "body" : 
          { "type" : "html", "content" : "" },  
     "runs" : 0  
   } ] 
  }

希望只是抓住花括号之间的所有东西。但是,当我执行此操作时,它会抓取从第一个左括号 第一个 结束括号的所有内容。为了扩展性,我只想抓住第一个左大括号和 最后 结束括号内的所有内容。

从技术上讲,它可以从第一个开始大括号开始并返回所有内容直到响应结束(JSON之后没有任何内容)。

思想?

2 个答案:

答案 0 :(得分:13)

正则表达式很棒,但绝对不是正确的工具。

有一个函数json_decode()可以为你处理。

它将结构作为对象返回。您可以通过将第二个参数设置为TRUE将其作为数组返回。即使PHP没有这个功能,你最好还是编写或使用现有的JSON解析器,而不是试图用正则表达式提取部分。

如果您正在使用标题并需要将正文分隔为单独的变量,则应执行以下操作:$ch是curl的实例,而$result是{{1}的返回1}}。

curl_exec()

答案 1 :(得分:2)

因为这有助于我接近结果但只是“附近”想要分享我的结果..

$json = array ( "firstname" => "john" , "lastname" => "Doe") ; 
$jsonheader = array ( "Accept: application/json" 
, "Content-type:application/json" 
, "Authorization: OAuth oauth_token=xxxxx" ) ;

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://myurl.com?oAuth=12341231234' ); // set the target url
curl_setopt($ch, CURLOPT_POST, 1 ); // howmany parameter to post
curl_setopt($ch, CURLOPT_POSTFIELDS, $json ); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true ); // don't give anything back 
curl_setopt($ch, CURLOPT_HEADER, TRUE );  // need this to evaluate the response .. 
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $jsonheader ); // it is httpheader not httpheader"s" 

$result = curl_exec ($ch);

curl_close ($ch);
$resultarr = explode ( "\n" , $result ) ;
$httpval = explode ( " " , $resultarr[0] ) ; // explode the first line

for ( $i=1 ;  $i < count( $resultarr) ; $i++ ) {
    if ( is_array (json_decode( $resultarr[$i] , true)) ){
        $resultvals  = json_decode( $resultarr[$i] , true) ;
    }       
}
if ( $resultvals['YourKey'] <> '' ) {  // any accepted value in the response ... 
    if ( $httpval[1] == "201" )  {
        $error = 0 ; //  no error Overwrite error 2 
    } else {
        $error = 1 ;  // http response was not 201  .. 
    }
} else {
   $error = 2 ;  // any other error like "no response" or "other error"   
 }