0

I'm trying to explain to a php developer how to consume our web service. There is a bit of a language barrier, but essentially it works by POSTing xml data straight to a url. Here's how you do it in C#, which works just fine;

public string POSTXml(string xml, string url)
{
    WebRequest req = null;
    WebResponse rsp = null;
    try
    {
        StringBuilder strRequest = new StringBuilder();                       

        req = WebRequest.Create(url);
        req.Method = "POST";        
        req.ContentType = "text/xml";     

        StreamWriter writer = new StreamWriter(req.GetRequestStream());
        writer.WriteLine(xml);
        writer.Close();

        rsp = req.GetResponse();

        var sr = new StreamReader(rsp.GetResponseStream());
        string responseText = sr.ReadToEnd();

        return responseText;

    }
    catch (Exception e)
    {
        throw new Exception("There was a problem sending the message");
    }
}

The developer is having trouble doing this in php. Is anyone able to translate the above code into php?

Also, I inherited this code from my predecessor and if I'm being honest I've never seen a web service implented in this way... I'm starting to worry that it's me not explaining it very well (I just tell people to POST the xml straight to the url i give them, and around 80% of them get it straight away and the other 20% get confused!). Is anyone able to give me a better explanation that more people might understand?

3

2 Answers 2

1

Hope this helps.

<?php

// Some code borrowed from http://www.php.net/manual/en/function.curl-exec.php
$url = 'http://www.example.com/';
$xml = '<?xml version="1.0"?><data>x</data>';

try
{
    $ch = curl_init();
    // set URL and other appropriate options
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
    curl_setopt($ch, CURLOPT_TIMEOUT, 4);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: close'));
    curl_exec($ch);

    if (curl_errno($ch))
    {
        throw new Exception(curl_errno($ch) . ': ' . curl_error($ch));
    }
    else
    {
        $result = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
        if ($returnCode == 404)
        {
            throw new Exception('URL Invalid');
        }
    }

    curl_close($ch);

    echo $result;
}
catch (Exception $exception)
{
    echo '[Error Message] ' . $exception->getMessage();
}
0

How about this:

http://www.codediesel.com/php/posting-xml-from-php/

It uses CURL so should be in line with what he's after

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.