2014-10-17 78 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响应)。欢迎任何意见/建议。