Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Mabloq's avatar

How do I generate an XML file from MYSQL table

I'm trying to add a Google Maps Api to my site.

The docs(https://developers.google.com/maps/documentation/javascript/mysql-to-maps) recommend that I write the data from Mysql to an XML file then use JS to parse the xml file and display that data on the google map that I want to design.

However I don't want to do this in plain php, whats the Laracasts way to write to an xml file?

So far All I can think of is this:

public function() { 

$path = FileSystem::(path/to/maps.xml); 

$contents = Maps::all();

File::put($path,$contents);

}

would that work?

0 likes
2 replies
mikefolsom's avatar

It depends on how often the data changes. if it is relatively static (e.g. store locations), then writing an XML file to the filesystem would be fine. Otherwise, you probably need to generate the XML dynamically (probably with an appropriate cache length) and output it directly in your response.

Either way, there is nothing wrong with using "plain" PHP and its built-in XML tools to generate your XML data from Eloquent collections.

1 like
Mabloq's avatar
Mabloq
OP
Best Answer
Level 1

Thanks, you're right. There is nothing wrong with using plain PHP. Ive found that using PHP's XmlWriter module for building static xml files from eloquent models is super fast and works great.

Also for making future entires into the xml file i now use PHP's built in SimpleXml module to insert new elements as I update my database.

For those of you who may want to implement the static version...

    $projects = Project::all();
      $xml = new \XMLWriter();
      $xml->openMemory();
      $xml->setIndent(true);
    // Start a new document
      $xml->startDocument();
    // Start a element to put data in
      $xml->startElement('projects');
    // Data what goes in your element\
      foreach ($projects as $project) {
        $xml->startElement('project');
        $xml->writeAttribute('id', $project->id);
        $xml->writeAttribute('name', $project->name);
        $xml->writeAttribute('address', $project->address);
        $xml->writeAttribute('lat', $project->lat);
        $xml->writeAttribute('lng', $project->lng);
        $xml->writeAttribute('type', $project->type);
        $xml->endElement();
      }

      $xml->endElement();
      $xml->endDocument();

    // You put the XML content in this variable
    $contents = $xml->outputMemory();
    // Reset XML just in case
    $xml = null;

    Storage::put('projects.xml',$contents);

Please or to participate in this conversation.