I'm currently using a scientific information management system that employs a RESTful API. I've never used this API with PHP, and I had a hard time finding best practice examples online. After some reading and experimenting, I came up with the following proof-of-concept procedure to retrieve data from the API and then upload the XML object, slightly modified, in order to change information in the system.
I'm most concerned with PHP best practices here: is my PHP efficient, robust, and secure? Is there any code I can remove or make more efficient? I'm using PHP v5.3.8
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php
$uriPrefix = 'http://[user:pass]@[path_to_web_app:port]/api/v2/';
//Open up a connection to the API
//for the container:
$containerSuffix = 'containers/27-95';
$containerUri = $uriPrefix . $containerSuffix;
$containerCurl = curl_init($containerUri);
//for the sample:
$sampleSuffix = 'samples/DOR6A12';
$sampleUri = $uriPrefix . $sampleSuffix;
$sampleCurl = curl_init($sampleUri);
//API-specific settings
curl_setopt($containerCurl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($sampleCurl, CURLOPT_RETURNTRANSFER, true);
//get the yummy data
$containerResult = curl_exec($containerCurl);
$containerXml = new SimpleXMLElement($containerResult);
$sampleResult = curl_exec($sampleCurl);
$sampleXml = new SimpleXMLElement($sampleResult);
//close the API connection
curl_close($containerCurl);
curl_close($sampleCurl);
echo '<h2>Some XML for a LIMS Container:</h2>';
echo htmlentities($containerXml->asXML());
echo '<h2>Some XML for a LIMS Sample:</h2>';
echo htmlentities($sampleXml->asXML());
//Now let's infer the project ID for the sample from the XML result
$limsId = $sampleXml->project['limsid'];
echo "<p>The project ID for the sample is $limsId</p>";
//Now let's change the sample name
$newName = 'New Sample Name';
$oldName = (string)$sampleXml->name;
$sampleXml->name = $newName;
$changeSampleCurl = curl_init($sampleUri);
curl_setopt($changeSampleCurl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($changeSampleCurl, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($changeSampleCurl, CURLOPT_POSTFIELDS,$sampleXml->asXML());
$changeSampleResult = curl_exec($changeSampleCurl);
echo '<h2>The submitted XML</h2>';
echo htmlentities($changeSampleResult);
curl_close($changeSampleCurl);
echo "<p>The old sample name was $oldName</p>";
echo "<p>It should now be $newName</p>";
?>
</body>
</html>