I’m working on a code to generate a php file.
This is example of my code to write the php file
$myFile = "testFile.php";
$fh = fopen($myFile, 'w+') or die("can't open file");
$data = '<?php'. "\n\n";
$data.= '$datetime = date("Y-m-d H:i:s");'. "\n\n";
$data.= '$_POST = array_map(\'mysql_real_escape_string\', $_POST);'. "\n\n";
$data.= '?>';
fwrite($fh, $data);
fclose($fh);
This code works fine. My question is there any smarter way to write a php code into a file? For example i have this function i would like to write into the php file. It would be very tedious to write all the function line by line like what i’m doing right now.
function shorten_url($url)
{
$longUrl = $url;
$apiKey = 'your_api_key_here';
$postData = array('longUrl' => $longUrl, 'key' => $apiKey);
$jsonData = json_encode($postData);
$curlObj = curl_init();
curl_setopt($curlObj, CURLOPT_URL, 'https://www.googleapis.com/urlshortener/v1/url');
curl_setopt($curlObj, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curlObj, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curlObj, CURLOPT_HEADER, 0);
curl_setopt($curlObj, CURLOPT_HTTPHEADER, array('Content-type:application/json'));
curl_setopt($curlObj, CURLOPT_POST, 1);
curl_setopt($curlObj, CURLOPT_POSTFIELDS, $jsonData);
$response = curl_exec($curlObj);
$json = json_decode($response);
curl_close($curlObj);
$tiny_url = $json->id;
if(($response!=FALSE)&&(!empty($tiny_url)))
{
return $tiny_url;
}
else
{
return false;
}
}
If you have PHP >= 5.3, using the
nowdoc syntaxfor this would be much more convenient: