patternphpMinor
Generating code with XML
Viewed 0 times
codegeneratingwithxml
Problem
I'm working on my graduate project and I had stumbled upon a somewhat dilemma, I've managed to solve it with some workarounds but I have my doubts that this is the most efficient way to deal with this problem.
I'm writing a class to deal with the Plesk API and making it as flexible as possible for easy use.
Here is the function for generating the XML that will be send out as request:
Here's my public function:
```
public function createEmail($host, $domain, $params){
$curl = $this->curlInit($host);
$packet = $this->emailCreatePacket($domain, $params);
echo $packet;
$re
I'm writing a class to deal with the Plesk API and making it as flexible as possible for easy use.
Here is the function for generating the XML that will be send out as request:
private function emailCreatePacket($domain, $params){
// Create new XML document.
$xml = new DomDocument('1.0', 'UTF-8');
$xml->formatOutput = true;
// Create packet
$packet = $xml->createElement('packet');
$packet->setAttribute('version', '1.4.2.0');
$xml->appendChild($packet);
$mail = $xml->createElement('mail');
$packet->appendChild($mail);
$create = $xml->createElement('create');
$mail->appendChild($create);
$filter = $xml->createElement('filter');
$create->appendChild($filter);
$domain_id = $xml->createElement('domain_id', $domain->id);
$filter->appendChild($domain_id);
$mailname = $xml->createElement('mailname');
$filter->appendChild($mailname);
foreach ($params as $key => $value) {
$node = $mailname;
if(strpos($key, ':') !== false){
$split = explode(':', $key);
$key = $split[1];
$node = ${$split[0]};
if(!isset(${$split[0]})){
${$split[0]} = $xml->createElement($split[0]);
$mailname->appendChild(${$split[0]});
}
$xmlelement = $xml->createElement($key, $value);
${$split[0]}->appendChild($xmlelement);
}else{
$xmlelement = $xml->createElement($key, $value);
$node->appendChild($xmlelement);
}
}
return $xml->saveXML();
}Here's my public function:
```
public function createEmail($host, $domain, $params){
$curl = $this->curlInit($host);
$packet = $this->emailCreatePacket($domain, $params);
echo $packet;
$re
Solution
Generally speaking, I like your code. I think it's well planned with few inefficiencies. I'm also impressed by your use of PHP's
DOMDocument class. When creating XML via PHP, I usually opt for foreach loops and output buffering. I've been aware of this object class, but your example is the first I've ever seen it put to use. +1 for showing me something new! :DContext
StackExchange Code Review Q#1368, answer score: 2
Revisions (0)
No revisions yet.