1) Estás abriendo el archivo para escritura en lugar de lectura como debería ser, aqui: $fd = fopen ($filename, "w");
Prueba este ejemplo:
Código PHP:
<?php
//Agregamos el HEAD :D
$filename = "g.php";
$fd = fopen ($filename, "r");
$Contenido = fread ($fd, filesize ($filename));
fclose ($fd);
$Contenido.="<?\r\n";
$Contenido.="
<html>
<head>
<title>Documento sin título</title>
<meta http-equiv='Content-Type' content='text/html; charset=iso-8859-1'>
</head>
<body>
linkfdsfdsfsd
</body>
</html>";
$Contenido.="?>\r\n";
//Grabamos el archivo y cerramos :D
$fp=fopen("ruta/nombre_archivo","w+");
fwrite($fp,$Contenido,strlen($Contenido));
fclose($fp);
?>
2) haz las consultas a la base y concatena los resultados a la variable $Contenido en el lugar correspondiente.