This is a fragment of code from one of my projects, I have looked up ways to creating XML documents with php and found suggestions to use SimpleXMLElement or DOMDocument but is there anything wrong with the below approach? it seems much more simple.
Note: the whole point of this question is to get the pros and cons of each approach even though all of them will work.
public function getXML() {
$sc = function($str) {
return htmlspecialchars($str, ENT_QUOTES);
};
$XMLString = '<?xml version="1.0" encoding="UTF-8" ?>'
. '<playlist>'
. '<id>' . $sc($this->getID()) . '</id>'
. '<title>' . $sc($this->getTitle()) . '</title>'
. '<description>' . $sc($this->getDescription()) . '</description>'
. '<numVideos>' . $sc($this->getNumOfVideos()) . '</numVideos>';
foreach ($this->videoList as $v) {
$XMLString.= '<video>'
. '<id>' . $sc($v->getID()) . '</id>'
. '<title>' . $sc($v->getTitle()) . '</title>'
. '<duration>' . $sc($v->getDuration()) . '</duration>'
. '<thumbnail>' . $sc($v->getThumbnail()) . '</thumbnail>'
. '<datePublished>' . $sc($v->getDatePublished()) . '</datePublished>'
. '<description>' . $sc($v->getDescription()) . '</description>'
. '<views>' . $sc($v->getViews()) . '</views>'
. '<favorites>' . $sc($v->getFavorites()) . '</favorites>'
. '<numRated>' . $sc($v->getNumRaters()) . '</numRated>'
. '<author>' . $sc($v->getAuthor()) . '</author>'
. '</video>';
}
$XMLString.= "</playlist>";
return $XMLString
}
Verses
public function getXML() {
$sc = function($str) {
return htmlspecialchars($str, ENT_QUOTES);
};
$playlist = new SimpleXMLElement("<playlist></playlist>");
$playlist->addChild("id", $sc($this->getID()));
$playlist->addChild("title", $sc($this->getTitle()));
$playlist->addChild("description", $sc($this->getDescription()));
$playlist->addChild("numVideos", $sc($this->getNumOfVideos()));
foreach ($this->videoList as $k => $v) {
$videos = $playlist->addChild("videos");
$videos->addChild('id', $sc($v->getID()));
$videos->addChild('title', $sc($v->getTitle()));
$videos->addChild('duration', $sc($v->getDuration()));
$videos->addChild('thumbnail', $sc($v->getThumbnail()));
$videos->addChild('datePublished', $sc($v->getDatePublished()));
$videos->addChild('description', $sc($v->getDescription()));
$videos->addChild('views', $sc($v->getViews()));
$videos->addChild('favorites', $sc($v->getFavorites()));
$videos->addChild('numRated', $sc($v->getNumRaters()));
$videos->addChild('author', $sc($v->getAuthor()));
}
return $playlist->asXML();
}