[GIS] How to use PHP MapScript to generate a MapServer Mapfile

mapfilemapscriptmapserverPHP

I just read from this question that the OP was

using Mapscript and C# to generate and display a Mapfile

I was wondering if it is really possible to use MapScript to generate a Mapfile? And if so, is there an example of doing so with PHP MapScript?

P.S. I am new to MapServer, and I feel that manually writing every mapfile's is a pain even if I learn all its grammar. It would be nice if a bunch of mapfiles can be generated from a program by varying certain parameters.

If MapScript isn't the solution, is there any other way to generate mapfiles programmatically?

P.S.2. This post asks a similar question about doing it in python, but there seems to be no solution in the answers.

Thanks in advance,

— EDIT —

Just to clarify, I am interested in writing/serialization of Mapscript objects into a mapfile (in PHP), not writing a mapfile verbatim via a programming languages such as PHP or C++. From the SO question quoted, this seems possible in C#. I was asking whether there are specific examples of actually doing that (preferably in PHP).

Best Answer

Ok, this is not really a GIS related but rather a programming related question. Anyway, for your intended purpose you can use almost any language you like. Here is a very, very simple PHP script based on the example Mapfile from the documentation at http://www.mapserver.org/mapscript/php/by_example.html. In this script only the variable DATA is altered:

<?php

foreach(['map1', 'map2', 'map3'] as $mapname) {

    $tpl = "NAME \"Europe in purple\"
SIZE 400 400
STATUS ON
SYMBOLSET \"/var/www/html/maps/symbols/symbols.sym\"
EXTENT -5696501 1923039 5696501 11022882
UNITS METERS
SHAPEPATH \"/var/www/html/maps/data\"

WEB
    IMAGEPATH \"/var/www/html/maps/tmp/\"
    IMAGEURL \"/tmp/\"
END

LAYER
    NAME \"Europe\"
    TYPE POLYGON
    STATUS ON
    DATA \"$mapname\"
    CLASS
        STYLE
            COLOR 110 50 100
            OUTLINECOLOR 200 200 200
            SYMBOL 0
        END
    END
END
END";

    // Write it to a file
    $handle = fopen("mapfile_$mapname", 'a');
    fwrite($handle, $tpl);

}

?>

Run the script with php script.php.