RPeraltaJr
2/6/2020 - 6:52 PM

Database Results to XML

<?php 

include basename(__DIR__) . '/../../includes/db.php';

// * fetch data from table
$table_name = "jobs";
$query = $db->prepare("SELECT * FROM $table_name");
$query->execute();
$results = $query->fetchAll();

// * serve xml doc as xml
header('Content-type: application/xml');

// * begin setup for XML file
$xml = new XMLWriter();
$xml->openURI("php://output");
$xml->startDocument();
$xml->setIndent(true);


// * fetch data and convert to XML nodes
$xml->startElement('Jobs');
    foreach($results as $row): 
        $row = (object) $row;

        // format title for url
        $formatted_title = str_replace(array(" ", ","), "-", strtolower($row->title));

        $job_id = htmlspecialchars($row->job_id);
        $url = htmlspecialchars("https://careers.draftkings.com/apply?id={$row->job_id}&title=$formatted_title");
        $title = htmlspecialchars($row->title);
        $department = htmlspecialchars($row->department);
        $team = htmlspecialchars($row->team);
        $location = htmlspecialchars($row->location);
        $commitment = htmlspecialchars($row->commitment);
        $created_at = htmlspecialchars($row->created_at);

        $xml->startElement("Job");
            $xml->startElement("id");
                // $xml->writeAttribute('udid', $row->job_id);
                $xml->writeRaw($job_id);
            $xml->endElement();
            $xml->startElement("title");
                $xml->writeRaw($title);
            $xml->endElement();
            $xml->startElement("url");
                $xml->writeRaw($url);
            $xml->endElement();
            $xml->startElement("department");
                $xml->writeRaw($department);
            $xml->endElement();
            $xml->startElement("team");
                $xml->writeRaw($team);
            $xml->endElement();
            $xml->startElement("location");
                $xml->writeRaw($location);
            $xml->endElement();
            $xml->startElement("commitment");
                $xml->writeRaw($commitment);
            $xml->endElement();
            $xml->startElement("description");
                $xml->writeCData($row->description);
            $xml->endElement();
            $xml->startElement("list");
                $xml->writeCData($row->list);
            $xml->endElement();
            $xml->startElement("additional");
                $xml->writeCData($row->additional);
            $xml->endElement();
            $xml->startElement("created_at");
                $xml->writeRaw($created_at);
            $xml->endElement();
        $xml->endElement();
    endforeach;
$xml->endElement();


$xml->flush();