What are best practices for ensuring correct syntax in zonefiles generated by PHP for Bind?

To ensure correct syntax in zonefiles generated by PHP for Bind, it is important to properly format the records with the correct syntax, including the use of tabs for indentation and ensuring each record ends with a semicolon. Additionally, it is recommended to validate the generated zonefile using a tool like named-checkzone to catch any syntax errors before loading it into Bind.

$zonefile = "example.com.zone";
$records = [
    "example.com. IN SOA ns1.example.com. admin.example.com. (",
    "            2022010101 ; Serial",
    "            3600       ; Refresh",
    "            1800       ; Retry",
    "            604800     ; Expire",
    "            86400 )    ; Minimum TTL",
    "example.com. IN NS ns1.example.com.",
    "example.com. IN NS ns2.example.com.",
    "ns1.example.com. IN A 192.168.1.1",
    "ns2.example.com. IN A 192.168.1.2",
];

$fh = fopen($zonefile, 'w');
foreach ($records as $record) {
    fwrite($fh, $record . PHP_EOL);
}
fclose($fh);

// Validate the zonefile
exec("named-checkzone example.com $zonefile", $output, $return_var);
if ($return_var !== 0) {
    echo "Error: Zonefile has syntax errors.";
}