Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When writing XML, is it better to hand write it, or to use a generator such as simpleXML in PHP?

I have normally hand written xml like this:

<tag><?= $value ?></tag>

Having found tools such as simpleXML, should I be using those instead? What's the advantage of doing it using a tool like that?

like image 790
Rich Bradshaw Avatar asked Sep 26 '08 13:09

Rich Bradshaw


4 Answers

Good XML tools will ensure that the resulting XML file properly validates against the DTD you are using.

Good XML tools also save a bunch of repetitive typing of tags.

like image 75
DGentry Avatar answered Nov 15 '22 12:11

DGentry


If you're dealing with a small bit of XML, there's little harm in doing it by hand (as long as you can avoid typos). However, with larger documents you're frequently better off using an editor, which can validate your doc against the schema and protect against typos.

like image 33
Danimal Avatar answered Nov 15 '22 13:11

Danimal


You could use the DOM extenstion which can be quite cumbersome to code against. My personal opinion is that the most effective way to write XML documents from ground up is the XMLWriter extension that comes with PHP and is enabled by default in recent versions.

$w=new XMLWriter();
$w->openMemory();
$w->startDocument('1.0','UTF-8');
$w->startElement("root");
    $w->writeAttribute("ah", "OK");
    $w->text('Wow, it works!');
$w->endElement();
echo htmlentities($w->outputMemory(true));
like image 34
Stefan Gehrig Avatar answered Nov 15 '22 13:11

Stefan Gehrig


using a good XML generator will greatly reduce potential errors due to fat-fingering, lapse of attention, or whatever other human frailty. there are several different levels of machine assistance to choose from, however:

  1. at the very least, use a programmer's text editor that does syntax highlighting and auto-indentation. just noticing that your text is a different color than you expect, or not lining up the way you expect, can tip you off to a typo you might otherwise have missed.

  2. better yet, take a step back and write the XML as a data structure of whatever language you prefer, than convert that data structure to XML. Perl gives you modules such as the lightweight XML::Simple for small jobs or the heftier XML::Generator; using XML::Simple is just a matter of arranging your content into a standard Perl hash of hashes and running it through the appropriate method.

-steve

like image 2
hakamadare Avatar answered Nov 15 '22 13:11

hakamadare