2014-10-17 21 views
0

我一直在使用API​​,我曾經運行cron作業並每5分鐘進行一次API調用。最近,他們引入了一個類似於PayPal IPN的功能,該功能在訂單得到響應後發佈變量。PHP:解析包含多部分表單數據的帖子響應

我確實打印了帖子變量,並郵寄它來查看響應的內容。這是我使用的代碼。

$post_var = "Results: " . print_r($_POST, true); 
mail('[email protected]', "Post Variables", $post_var); 

我收到了這封信。

Results: Array 
(
    [--------------------------918fc8da7040954f 
Content-Disposition:_form-data;_name] => "ID" 

1 
--------------------------918fc8da7040954f 
Content-Disposition: form-data; name="TXN" 

1234567890 
--------------------------918fc8da7040954f 
Content-Disposition: form-data; name="Comment" 

This is a test comment 
--------------------------918fc8da7040954f 
Content-Disposition: form-data; name="ConnectID" 

1 
--------------------------918fc8da7040954f 
Content-Disposition: form-data; name="ConnectName" 

Test Connect (nonexisting) 
--------------------------918fc8da7040954f 
Content-Disposition: form-data; name="Status" 

Unavailable 
--------------------------918fc8da7040954f 
Content-Disposition: form-data; name="CallbackURL" 

http://www.example.com/ipn 
--------------------------918fc8da7040954f-- 

) 

現在我需要ID的值,即1,TXN,即1234567890等,我從來沒有與這些類型的數組一起工作。我如何繼續,我實際得到的迴應是什麼。這是一個cUrl響應還是多部分表單數據響應?

如果可能請請向我解釋。

回答

0

即使這個問題是6個月大,我會在這裏添加我的迴應,因爲我剛剛有這個確切的問題,並且無法在線找到簡單的解析器。

假設$response包含您的多部分內容:

// Match the boundary name by taking the first line with content 
preg_match('/^(?<boundary>.+)$/m', $response, $matches); 

// Explode the response using the previously match boundary 
$parts = explode($matches['boundary'], $response); 

// Create empty array to store our parsed values 
$form_data = array(); 

foreach ($parts as $part) 
{ 
    // Now we need to parse the multi-part content. First match the 'name=' parameter, 
    // then skip the double new-lines, match the body and ignore the terminating new-line. 
    // Using 's' flag enables .'s to match new lines. 
    $matched = preg_match('/name="?(?<key>\w+).*?\n\n(?<value>.*?)\n$/s', $part, $matches); 

    // Did we get a match? Place it in our form values array 
    if ($matched) 
    { 
     $form_data[$matches['key']] = $matches['value']; 
    } 
} 

// Check the response... 
print_r($form_data); 

我敢肯定有很多需要注意的地方,以這種方法,使您的里程可能會有所不同,但它滿足了我的需要(解析到位桶片段API響應)。歡迎任何意見/建議。

相關問題