1

I have been working with an API and I used to run a cron job and make an API call every 5 minutes. Recently they introduced an feature similar to PayPal IPN which posts variables once the order gets response.

I did print the post variables and mailed it to have a look at what the response would be. This is the code I used.

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

and I got this in the mail.

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--

)

Now I need the values of ID i.e. 1, TXN i.e. 1234567890 etc., I never worked with these kind of array. How do I proceed and what is the response I have actually got. Is this a cUrl response or multipart form data response?

Please explain it to me if possible.

1 Answer 1

1

Assuming $response contains your multi-part content:

// 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);

I'm sure there's a lot of caveats to this approach so your mileage may vary, but it satisfied my need (parsing a BitBucket snippet API response).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.