user982124
user982124

Reputation: 4610

PHP - Convert incoming HTTP POST into variables

I'm working with a web service that is submitting an HTTP POST to a PHP page as follows:

FORM/POST PARAMETERS: None

HEADERS: Content-Type: text/xml

BODY:

<?xml version="1.0"?>
 <mogreet>
  <event>message-in</event>
  <type>command_sms</type>
   <campaign_id>12345</campaign_id>
   <shortcode>123456</shortcode>
  <msisdn>15552345678</msisdn>
  <carrier><![CDATA[T-Mobile]]></carrier>
  <carrier_id>2</carrier_id>
  <message><![CDATA[xxxx testing]]></message>
 </mogreet>

I need to be able to convert each of the XML elements into PHP variables so I can update a database. I've never had to work with an incoming POST with XML data before and not sure where to starT - I am familiar with processing incoming GET/POST requests but not raw xml.

Upvotes: 3

Views: 637

Answers (3)

Christian Gollhardt
Christian Gollhardt

Reputation: 17004

Take a look at SimpleXMLElement:

http://php.net/manual/de/class.simplexmlelement.php

$xmlstr = $_POST['key'];
$xml = new SimpleXMLElement($xmlstr);
//work with $xml like this:
$event = $xml->mogreet->event;

You can see the key if you do this:

print_r($_POST);

Most times, we work with this kind of api, we want to log it, because we can not see it:

$debugFile = 'debug.log'
file_put_contents($debugFile, print_r($_POST, true), FILE_APPEND);

Take also a look at the Answer from Matt Browne, for getting Raw Input.

Upvotes: 0

l&#39;L&#39;l
l&#39;L&#39;l

Reputation: 47169

This will eliminate all the SimpleXMLElement objects and return your array:

from an xml string:

<?php

$xml='<?xml version="1.0"?>
<mogreet>
<event>message-in</event>
<type>command_sms</type>
<campaign_id>12345</campaign_id>
<shortcode>123456</shortcode>
<msisdn>15552345678</msisdn>
<carrier><![CDATA[T-Mobile]]></carrier>
<carrier_id>2</carrier_id>
<message><![CDATA[xxxx testing]]></message>
</mogreet>';

$xml = simplexml_load_string($xml);
$xml_array = json_decode(json_encode((array) $xml), 1);

print_r($xml_array);

?>

from an xml file:

$xml = simplexml_load_file("mogreet.xml");

$xml_array = json_decode(json_encode((array) $xml), 1);

print_r($xml_array);

output:

Array
(
    [event] => message-in
    [type] => command_sms
    [campaign_id] => 12345
    [shortcode] => 123456
    [msisdn] => 15552345678
    [carrier] => Array
        (
        )

    [carrier_id] => 2
    [message] => Array
        (
        )

)

Upvotes: 0

Matt Browne
Matt Browne

Reputation: 12419

I think you'll need to use $HTTP_RAW_POST_DATA. After that then you could use SimpleXMLElement as @ChristianGolihardt suggested.

Note that HTTP_RAW_POST_DATA is only available if the always_populate_raw_post_data setting has been enabled in php.ini. Otherwise, it may be easiest to do this:

$postData = file_get_contents("php://input");
...
$xml = new SimpleXMLElement($postData);
...

Upvotes: 1

Related Questions