I am trying to include file in string replace but in output i am getting string not the final output.
analytic.php
<?php echo "<title> Hello world </title>"; ?>
head.php
<?php include "analytic.php"; ?>
index.php
string = " <head> </head>";
$headin = file_get_contents('head.php');
$head = str_replace("<head>", "<head>". $headin, $head);
echo $head;
Output i am getting :
<head><?php include "analytic.php"; ?> </head>
Output i need :
<head><title> Hello world </title> </head>
Note : Please do not recommend using analytic.php directly in index.php because head.php have some important code and it has to be merged analytic.php with head.php and then index.php
To get the desired output :
function getEvaluatedContent($include_files) {
$content = file_get_contents($include_files);
ob_start();
eval("?>$content");
$evaluatedContent = ob_get_contents();
ob_end_clean();
return $evaluatedContent;
}
$headin = getEvaluatedContent('head.php');
string = " <head> </head>";
$head = str_replace("<head>", "<head>". $headin, $head);
echo $head;
Output will be output string not file string :
<head><title> Hello world </title> </head>
I think your approach is pretty basic (you try to hardcore modify - programmerly edit - the template script, right?) but anyway:
$file = file('absolut/path/to/file.php');
foreach ($file as $line => $code) {
if (str_contains($code, '<head>')) {
$file[$line] = str_replace('<head>', '<head>' . $headin, $code);
break;
}
}
file_put_contents('absolut/path/to/file.php', $file);
Related
I'm creating a web app where I want to include JavaScript files with all file sources in an array, but I can't do that.
Header.php
<head>
<?php
$import_scripts = array(
'file01.js',
'file02.js'
);
foreach ($import_scripts as $script) {
echo '<script src="' . $script . '"></script>';
}
?>
</head>
<body>
Index.php
<?php
include('header.php');
array_push($import_scripts,'file03.js')
?>
But this only includes file01.js and file02.js, JavaScript files.
Your issue is that you've already echo'ed the scripts in headers.php by the time you push the new value into the array in index.php. So you need to add to extra scripts before you include headers.php. Here's one way to do it (using the null coalescing operator to prevent errors when $extra_scripts is not set):
header.php
<?php
$import_scripts = array_merge(array(
'file01.js',
'file02.js'
), $extra_scripts ?? []);
?>
<!DOCTYPE html>
<html>
<head>
<!-- Scripts Section -->
<?php
foreach ($import_scripts as $script) {
echo '<script src="' . $script . '"></script>' . PHP_EOL;
}
?><title>Demo</title>
</head>
<body>
<p>Blog</p>
index.php
<?php
$extra_scripts = ['file03.js'];
include 'header.php';
?>
Output (demo on 3v4l.org)
<!DOCTYPE html>
<html>
<head>
<!-- Scripts Section -->
<script src="file01.js"></script>
<script src="file02.js"></script>
<script src="file03.js"></script>
<title>Demo</title>
</head>
<body>
<p>Blog</p>
header.php
<?php
function scripts()
{
return [
'file01.js',
'file02.js'
];
}
function render($scripts)
{
foreach ($scripts as $script) {
echo '<script src="' . $script . '"></script>';
}
}
?>
<head>
index.php:
<?php
include 'header.php';
$extra_scripts = scripts();
$extra_scripts[] = 'script3.js';
render($extra_scripts);
?>
</head>
<body>
PHP is processed top down so it will currently be adding file03.js to the array after the foreach has been run.
This means you have two options:
Run the scripts after the header (Not reccomended)
Like Nick suggested, in index.php, specify additional scripts before the header is called
Other answers have answered why (you output content before adding the item to the array).
The best solution is to do all your processing before your output. Also helps with error trapping, error reporting, debugging, access control, redirect control, handling posts... as well as changes like this.
Solution 1: Use a template engine.
This may be more complex than you need, and/or add bloat. I use Twig, have used Smarty (but their site is now filled with Casino ads, so that's a concern), or others built into frameworks. Google "PHP Template engine" for examples.
Solution 2: Create yourself a quick class that does the output. Here's a rough, (untested - you will need to debug it and expand it) example.
class Page
{
private string $title = 'PageTitle';
private array $importScripts = [];
private string $bodyContent = '';
public setTitle(string $title): void
{
$this->title = $title;
}
public addImportScript(string $importScript): void
{
$this->importScripts[] = $importScript;
}
public addContent(string $htmlSafeBodyContent): void
{
$this->bodyContent .= $bodyContent;
}
public out(): void
{
echo '<!DOCTYPE html>
<html>
<head>
<!-- Scripts Section -->
';
foreach ($this->importScripts as $script) {
echo '<script src="' . htmlspecialchars($script) . '"></script>' . PHP_EOL;
}
echo '
<!-- End Scripts Section -->
<title>' . htmlspecialchars($this->title) . '</title>
</head>
<body> . $this->bodyContent . '
</body>
</html>';
exit();
}
}
// Usage
$page = new page();
$page->setTitle('My Page Title'); // Optional
$page->addImportScript('script1');
$page->addImportScript('script2');
$page->addContent('<h1>Welcome</h1>');
// Do your processing here
$page->addContent('<div>Here are the results</div>');
$page->addImportScript('script3');
// Output
$page->out();
I'd create a new php file, say functions.php and add the following code into it.
<?php
// script common for all pages.
$pageScripts = [
'common_1.js',
'common_2.js',
];
function addScripts(array $scripts = []) {
global $pageScripts;
if (!empty ($scripts)) { // if there are new scripts to be added, add it to the array.
$pageScripts = array_merge($pageScripts, $scripts);
}
return;
}
function jsScripts() {
global $pageScripts;
$scriptPath = './scripts/'; // assume all scripts are saved in the `scripts` directory.
foreach ($pageScripts as $script) {
// to make sure correct path is used
if (stripos($script, $scriptPath) !== 0) {
$script = $scriptPath . ltrim($script, '/');
}
echo '<script src="' . $script .'" type="text/javascript">' . PHP_EOL;
}
return;
}
Then change your header.php as
<?php
include_once './functions.php';
// REST of your `header.php`
// insert your script files where you needed.
jsScripts();
// REST of your `header.php`
Now, you can use this in different pages like
E.g. page_1.php
<?php
include_once './functions.php';
addScripts([
'page_1_custom.js',
'page_1_custom_2.js',
]);
// include the header
include_once('./header.php');
page_2.php
<?php
include_once './functions.php';
addScripts([
'./scripts/page_2_custom.js',
'./scripts/page_2_custom_2.js',
]);
// include the header
include_once('./header.php');
You are adding 'file03.js' to $import_scripts after including 'header.php', so echoing scripts it have been done yet. That's why 'file03.js' is not invoked.
So, you need to add 'file03.js' to $import_scripts before echoing scripts, this means before include 'header.php'.
A nice way is to move $import_scripts definition to index.php, and add 'file03.js' before including 'header.php'.
But it seems that you want to invoke certain JS scripts always, and add some more in some pages. In this case, a good idea is to define $import_scripts in a PHP file we can call init.php.
This solution will be as shown:
header.php
<head>
<?php
foreach ($import_scripts as $script) {
echo '<script src="' . $script . '"></script>';
}
?>
</head>
<body>
init.php
<?php
$import_scripts = array(
'file01.js',
'file02.js'
);
index.php
<?php
require 'init.php';
array_push($import_scripts,'file03.js');
include 'header.php';
header.php
<?php
echo "<head>";
$importScripts = ['file01.js','file02.js'];
foreach ($importScripts as $script) {
echo '<script src="' . $script . '"></script>';
}
echo "</head>";
echo "<body>";
index.php
<?php
include 'header.php';
array_push($importScripts, 'file03.js');
print_r($importScripts);
Output
Array ( [0] => file01.js [1] => file02.js [2] => file03.js )
I'm making an application to remove additive or commonly called Stemming confix stripping. I wanted to make a loop to process stemming in each text file. process stemming I've put them in the loop. making the process the content of each document also I put in a text file. when I run in the browser no error but only the note NULL. what's the solution? I attach my program and program results`it is code
<?php
require_once __DIR__ . '/vendor/autoload.php';
$array_sentence = glob('../../ujicoba/simpantoken/*.txt');
settype($array_sentence, "string");
if(is_array($array_sentence) && is_object($array_sentence))
{
foreach ($array_sentence as $text)
{
$textnormalizer = new src\Sastrawi\Stemmer\Filter\TextNormalizer();
$stemmerFactory = new \Sastrawi\Stemmer\StemmerFactory();
$stemmer = $stemmerFactory->createStemmer();
$content = file_get_contents($text);
$stemmer = $stemmerFactory->createStemmer();
$output = $stemmer->stem(array($content));
echo $output . "\n";
}
}
var_dump($content);
?>
<!DOCTYPE html>
<html>
<head>
<title>Confix Stripping Stemmer</title>
</head>
<body>
</body>
</html>
my source code result in browser when running programenter code here
On l.4, settype($array_sentence, "string"); force $array_sentence as a string, which means is_array($array_sentence) && is_object($array_sentence) will return false.
The following code works for stemming:
<?php
include('stopword.php');
$regexRules = array(
'/^be(.*)lah$/',
'/^be(.*)an$/',
'/^me(.*)i$/',
'/^di(.*)i$/',
'/^pe(.*)i$/',
'/^ter(.*)i$/',
'/^di(.*)kan$/',
'/^di(.*)nya$/',
'/^di(.*)kannya$/',
'/^mem(.*)pe$/',
'/^meng(.*)g$/',
'/^meng(.*)h$/',
'/^meng(.*)q$/',
'/^meng(.*)k$/',
'/^mem(.*)kan$/',
'/^diper(.*)i$/',
'/^di(.*)i$/',
'/^memper(.*)kan$/',
'/^meny(.*)i$/',
'/^meny(.*)kan$/',
'/^men(.*)kan$/',
'/^me(.*)kan$/',
'/^meng(.*)nya$/',
'/^memper(.*)i$/',
'/^men(.*)i$/',
'/^meng(.*)i$/',
'/^ber(.*)nya$/',
'/^ber(.*)an$/',
'/^ke(.*)an$/',
'/^ke(.*)annya$/',
'/^peng(.*)an$/',
'/^peny(.*)an$/',
'/^per(.*)an$/',
'/^pen(.*)an$/',
'/^pe(.*)an$/',
'/^ber(.*)$/',
'/^di(.*)$/',
'/^men(.*)$/',
'/^meng(.*)$/',
'/^meny(.*)$/',
'/^mem(.*)$/',
'/^pen(.*)$/',
'/^peng(.*)$/',
'/^ter(.*)$/',
'/^mem(.*)$/',
'/^(.*)nya$/',
'/^(.*)lah$/',
'/^(.*)pun$/',
'/^(.*)kah$/',
'/^(.*)mu$/',
'/^(.*)an$/',
'/^(.*)kan$/',
'/^(.*)i$/',
'/^(.*)ku$/',
);
global $regexRules;
$file_string = glob('yourfoldertoseavedata_text/*.txt');
$string = array('(.*)');
foreach ($file_string as $data)
{
$string[] = file_get_contents($data);
$stemming = str_ireplace($regexRules,"", $string);
var_dump($stemming);
}
?>
I have the following code that opens a non-txt file and runs through it so it can read the file line by line, i want to create a textbox (using html probably) so i can put my readed text into that but i have no idea how to do it
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
</head>
<body>
<h2>testing</h2>
<?php
$currentFile = "pathtest.RET";
$fp = fopen($currentFile , 'r');
if (!$fp)
{
echo '<p> FILE NOT FOUND </p>';
exit;
}
else
{
echo '<p><strong> Arquivo:</strong> ['. $currentFile. '] </p>';
}
$numLinha = 0;
while (!feof($fp))
{
$linha = fgets($fp,300);
$numLinha = $numLinha + 1;
echo $linha;
}
fclose($fp);
$numLinha = $numLinha -1;
echo '<hr>linhas processadas: ' . $numLinha;
?>
</body>
</html>
i need the textbox area to be in a form so i can define the cols and rows, or there is an way to do it in php ? is there any way to send the readed content to another .php so i can edit the php to an html interface style freely ?
Try echoing the lines between a textarea:
echo "<textarea>";
while (!feof($fp))
{
$linha = fgets($fp,300);
$numLinha = $numLinha + 1;
echo $linha;
};
echo "</textarea>";
You may use \n in order to break lines on the textarea:
echo $linha . "\n";
page.php:
<?php
include("header.php");
$title = "TITLE";
?>
header.php:
<title><?php echo $title; ?></title>
I want my title to be set after including the header file. Is it possible to do this?
expanding on Dainis Abols answer, and your question on output handling,
consider the following:
your header.php has the title tag set to <title>%TITLE%</title>;
the "%" are important since hardly anyone types %TITLE% so u can use that for str_replace() later.
then, you can use output buffer like so
<?php
ob_start();
include("header.php");
$buffer=ob_get_contents();
ob_end_clean();
$buffer=str_replace("%TITLE%","NEW TITLE",$buffer);
echo $buffer;
?>
and that should do it.
EDIT
I believe Guy's idea works better since it gives you a default if you need it, IE:
The title is now <title>Backup Title</title>
Code is now:
<?php
ob_start();
include("header.php");
$buffer=ob_get_contents();
ob_end_clean();
$title = "page title";
$buffer = preg_replace('/(<title>)(.*?)(<\/title>)/i', '$1' . $title . '$3', $buffer);
echo $buffer;
?>
1. Simply add $title variable before require function
<?php
$title = "Your title goes here";
require("header.php");
?>
2. Add following code into header.php
<title><?php echo $title; ?></title>
What you can do is, you store the output in a variable like:
header.php
<?php
$output = '<html><title>%TITLE%</title><body>';
?>
PS: You need to remove all echos/prints etc so that all possible output is stored in the $output variable.
This can be easely done, by defining $output = ''; at the start of the file and then find/replace echo to $output .=.
And then replace the %TITLE% to what you need:
<?php
include("header.php");
$title = "TITLE";
$output = str_replace('%TITLE%', $title, $output);
echo $output;
?>
Another way is using javascript in your code, instead of:
<title><?php echo $title; ?></title>
Put this in there:
<script type="text/javascript">
document.title = "<?=$title;?>"
</script>
Or jQuery, if you prefer:
<script type="text/javascript">
$(document).ready(function() {
$(this).attr("title", "<?=$title;?>");
});
</script>
Expanding a little on we.mamat's answer,
you could use a preg_replace instead of the simple replace and remove the need for a %title% altogether. Something like this:
<?php
ob_start();
include("header.php");
$buffer=ob_get_contents();
ob_end_clean();
$title = "page title";
$buffer = preg_replace('/(<title>)(.*?)(<\/title>)/i', '$1' . $title . '$3', $buffer);
echo $buffer;
?>
you can set using JavaScript
<script language="javascript">
document.title = "The new title goes here.";
</script>
Add this code on top your page
<?php
$title="This is the new page title";
?>
Add this code on your Template header file (include)
<title><?php echo $title; ?></title>
It's very easy.
Put this code in header.php
<?
$sitename = 'Your Site Name'
$pagetitle;
if(isset($pagetitle)){
echo "<title>$pagetitle." | ". $sitename</title>";
}
else {
echo "<title>$sitename</title>";
}
?>
Then in the page put there :
<?
$pagetitle = 'Sign up'
include "header.php";
?>
So if you are on Index.php , The title is Your Site Name.
And for example if you are on sign up page , The title is Sign up | Your Site Name
Every Simple just using a function , I created it .
<?
function change_meta_tags($title,$description,$keywords){
// This function made by Jamil Hammash
$output = ob_get_contents();
if ( ob_get_length() > 0) { ob_end_clean(); }
$patterns = array("/<title>(.*?)<\/title>/","<meta name='description' content='(.*)'>","<meta name='keywords' content='(.*)'>");
$replacements = array("<title>$title</title>","meta name='description' content='$description'","meta name='keywords' content='$keywords'");
$output = preg_replace($patterns, $replacements,$output);
echo $output;
}
?>
First of all you must create function.php file and put this function inside ,then make require under the MetaTags in Header.php .
To use this function change_meta_tags("NEW TITLE","NEW DESCRIPTION",NEW KEYWORDS); .
Don't use this function in Header.php !! just with another pages .
Use a jQuery function like this:
$("title").html('your title');
I know in php you can embed variables inside variables, like:
<? $var1 = "I\'m including {$var2} in this variable.."; ?>
But I was wondering how, and if it was possible to include a function inside a variable.
I know I could just write:
<?php
$var1 = "I\'m including ";
$var1 .= somefunc();
$var1 = " in this variable..";
?>
But what if I have a long variable for output, and I don't want to do this every time, or I want to use multiple functions:
<?php
$var1 = <<<EOF
<html lang="en">
<head>
<title>AAAHHHHH</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
</head>
<body>
There is <b>alot</b> of text and html here... but I want some <i>functions</i>!
-somefunc() doesn't work
-{somefunc()} doesn't work
-$somefunc() and {$somefunc()} doesn't work of course because a function needs to be a string
-more non-working: ${somefunc()}
</body>
</html>
EOF;
?>
Or I want dynamic changes in that load of code:
<?
function somefunc($stuff) {
$output = "my bold text <b>{$stuff}</b>.";
return $output;
}
$var1 = <<<EOF
<html lang="en">
<head>
<title>AAAHHHHH</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
</head>
<body>
somefunc("is awesome!")
somefunc("is actually not so awesome..")
because somefunc("won\'t work due to my problem.")
</body>
</html>
EOF;
?>
Well?
Function calls within strings are supported since PHP5 by having a variable containing the name of the function to call:
<?
function somefunc($stuff)
{
$output = "<b>{$stuff}</b>";
return $output;
}
$somefunc='somefunc';
echo "foo {$somefunc("bar")} baz";
?>
will output "foo <b>bar</b> baz".
I find it easier however (and this works in PHP4) to either just call the function outside of the string:
<?
echo "foo " . somefunc("bar") . " baz";
?>
or assign to a temporary variable:
<?
$bar = somefunc("bar");
echo "foo {$bar} baz";
?>
"bla bla bla".function("blub")." and on it goes"
Expanding a bit on what Jason W said:
I find it easier however (and this works in PHP4) to either just call the
function outside of the string:
<?
echo "foo " . somefunc("bar") . " baz";
?>
You can also just embed this function call directly in your html, like:
<?
function get_date() {
$date = `date`;
return $date;
}
function page_title() {
$title = "Today's date is: ". get_date() ."!";
echo "$title";
}
function page_body() {
$body = "Hello";
$body = ", World!";
$body = "\n\n";
$body = "Today is: " . get_date() . "\n";
}
?>
<html>
<head>
<title><? page_title(); ?></title>
</head>
<body>
<? page_body(); ?>
</body>
</html>