简体   繁体   中英

How to use a function inside a variable?

What I'm trying to do here is make use of PHP's ability to create and write to files because I have like 350 pages to make all with the same line of code that differs by one number. Much rather do this through code than manually creating 350 pages!

Each file will be (.php) and named after the title of the content it will have which has already been defined. However, as this will be the URL to reach the page, I need to format the title and use the formatted version as the filename.

This is what I've got to start with:

function seoUrl($string) {
  //Make lowercase
  $string = strtolower($string);
  //Clean up multiple dashes or whitespaces
  $string = preg_replace("/[\s-]+/", " ", $string);
  //Convert whitespaces and underscore to dash
  $string = preg_replace("/[\s_]/", "-", $string);
    return $string;
}

I found this function earlier on here and it worked perfectly for making the sitemap for all these pages. The URLs were just like I wanted. However, when I call the same function to do this for each title, I hit a snag. I assume I have the code wrong somewhere so here's a piece of the file creation code:

//Content title to be formatted for the filename
$title1="Capitalized And Spaced Title";

//Formatting
$urlfile1="seoUrl ($title1)";

//Text to be written
$txt1="<?include 'tpl/pages/1.txt'?>";

//And the create/write file code
  $createfile1=fopen("$urlfile1.php", "w");
      fwrite($createfile1, $txt1);
      fclose($createfile1);

The code inserts the $txt values just fine, which is actually where I anticipated having a problem. But my files that are created include the function name and parenthesis, plus the title isn't formatted.

I didn't have this problem on the sitemap page:

$url1="$domainurl/$pathurl/$title1.php";
$url2="$domainurl/$pathurl/$title2.php";
...

seoUrl($url1);
seoUrl($url2);
...

<?echo $url1?><br>
<?echo $url2?><br>
...

I've tried everything I can think of for the past couple hours now. What am I doing wrong here?

Try this i hope this might help you out. it will create file in proper format.

function seoUrl($string) {
//Make lowercase
$string = strtolower($string);
//Clean up multiple dashes or whitespaces
$string = preg_replace("/[\s-]+/", " ", $string);
//Convert whitespaces and underscore to dash
$string = preg_replace("/[\s_]/", "-", $string);
return $string;
}

$title1 = "Capitalized And Spaced Title";
//Formatting
$urlfile1 = seoUrl($title1);
//Text to be written
$txt1 = "<?include 'tpl/pages/1.txt'?>";
//And the create/write file code
$fileName = "" . $urlfile1 . ".php";
$createfile1 = fopen($fileName, "w");
fwrite($createfile1, $txt1);
fclose($createfile1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM