CPSC415A
Web Programming

Day 17 Notes

PHP XMLReader & XMLWriter

XML

<?xml version="1.0" encoding="UTF-8"?>
<useless>
  <entry verbosity="high">
    <one>this is the one tag data</one>
    <two>this is the two tag data</two>
  </entry>
  <entry verbosity="low">
    <one>1</one>
    <two>2</two>
  </entry>
</useless>

Reading XML

$reader = new XMLReader();
$reader->open("useless.xml");
while($reader->read()) {
    if ($reader->nodeType === XMLReader::ELEMENT) {
        print("Name: " . $reader->name);
        if ($reader->attributeCount > 0) {
            print("Verbosity: " . $reader->getAttribute("verbosity"));
        }
        print("</br />");
    }
    if ($reader->nodeType === XMLReader::TEXT) {
        print("Value: " . $reader->value . "<br />");
    }
}
$reader->close();

Writing XML

$writer = new XMLWriter();
$writer->openURI("useless.xml");
$writer->startDocument("1.0", "UTF-8");
$writer->startElement("entries");
$writer->writeAttribute("name", "value");
$writer->writeElement("one", "1");
$writer->endElement();
$writer->endDocument();
$writer->flush();