关于将 php 代码写入 .php 文件有什么技巧吗?
我正在编写生成 php 文件的代码。
这是我编写 php 文件的代码示例
$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);
此代码工作正常。我的问题是有没有更聪明的方法将 php 代码写入文件?例如,我有这个函数,我想写入 php 文件。像我现在正在做的那样逐行编写所有函数会非常乏味。
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;
}
}
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;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您的 PHP >= 5.3,请使用
nowdoc 语法
这样做会方便得多:If you have PHP >= 5.3, using the
nowdoc syntax
for this would be much more convenient:当然。
切勿以编程方式执行此操作。
Sure.
Never do it programmatically.