Category Archives: PHP - Page 5

Create XML document with PHP SimpleXML

In my work I often need to create new XML documents and with the introduction of SimpleXML in PHP 5.0.1 this has become very easy. Before PHP 5 I used the DOM-XML class which can be a little cumbersome for small and simple XML documents. I’m here going to create a simple XML document as an example of how I now normally do it.

$xml = new SimpleXMLElement('<?xml version="1.0" encoding="utf-8"?><mydoc></mydoc>');

$xml->addAttribute('version', '1.0');
$xml->addChild('datetime', date('Y-m-d H:i:s'));

$person = $xml->addChild('person');
$person->addChild('firstname', 'Someone');
$person->addChild('secondname', 'Something');
$person->addChild('telephone', '123456789');
$person->addChild('email', 'me@something.com');

$address = $person->addchild('address');
$address->addchild('homeaddress', 'Andersgatan 2, 432 10 Göteborg');
$address->addChild('workaddress', 'Andersgatan 3, 432 10 Göteborg');

echo $xml->asXML();

This will create a XML document looking like this:

<?xml version="1.0" encoding="utf-8"?>
<mydoc version="1.0">
  <datetime>2010-12-12 16:45:12</datetime>
  <person>
    <firstname>Anders</firstname>
    <lastname>Andersson</lastname>
    <telephone>123456789</telephone>
    <email>me@something.com</email>
    <address>
      <homeaddress>Andersgatan 2, 432 10 Göteborg</homeaddress>
      <workaddress>Andersgatan 3, 432 10 Göteborg</workaddress>
    </address>
  </person>
</mydoc>

Custom log to file function with log rotation and log levels

I often need logging in my applications so instead of inventing the wheel every time I decided to write a reusable log function. This is what I came up with (PHP 5.3.3)

/**
 * Log function with log file rotation
 * and loglevel restrictions
 *
 * @param <int> $level
 * @param <string> $event
 * @param <string> $text
 */
function logger($level, $event, $text = null){
        $maxsize = 5242880; //Max filesize in bytes (e.q. 5MB)
        $dir = "log/";
        $filename = "myapplication.log";
        $loglevel = 5;

        if(file_exists($dir.$filename) &&
                  filesize($dir.$filename) > $maxsize){
            $nb = 1;
            $logfiles = scandir($dir);
            foreach ($logfiles as $file) {                
                $tmpnb = substr($file, strlen($filename));
                if($nb < $tmpnb){
                    $nb = $tmpnb;
                }
            }
            rename($dir.$filename, $dir.$filename.($nb + 1));
        }
        if($level <= $loglevel) { 
           $data = date('Y-m-d H:i:s')." LEVEL: ".$level." ";
           $data .= "EVENT: ".$event." ".$text.PHP_EOL;
           file_put_contents($dir.$filename, $data, FILE_APPEND);
        }
}

This function will write a log row with a timestamp, error level, event name and error text (optional) to the logfile specified if the error level is below or equal to the general log level ($loglevel). If the logfile is bigger then $maxsize it vill rename the logfile by appending the next inline number to the end and create a new logfile.

Using PHP curl to PUT a string to a web service

With PHP curl function it is easy to PUT a file to a web service. However doing a PUT on a string is a little trickier. This is how I did it in PHP v5.1.6:

// The message
$message = "My little string of characters";

// Get the curl resource handle
$session = curl_init("http://localhost/myservice");

// Prepare message for PUT
$put_data = tmpfile(); //Get temporary filehandle
fwrite($put_data, $message); //Write the string to the temporary file
fseek($put_data, 0); //Put filepointer to the beginning of the temporary file

// Set the POST options
curl_setopt($session, CURLOPT_PUT, true); // Use PUT
curl_setopt($session, CURLOPT_HEADER, true); // Send header
curl_setopt($session, CURLOPT_RETURNTRANSFER, true); // Get response
curl_setopt($session, CURLOPT_INFILE, $put_data); // Set string data
curl_setopt($session, CURLOPT_INFILESIZE, strlen($message)); //Set data size

// Do the PUT and show the response
$response = curl_exec($session);
echo $response;

This will simply write my string ($message) to a php temporary file ($put_data). I then use this file when sending the data to the web service. NOTE: CURLOPT_HEADER and CURLOPT_RETURNTANSFER are optional.