open file and load text using php - php

I'm writing code and found a problem in taking data from file using php. So the goal is to take information from txt file and create div blocs. SO here I have on problem and one question, I hope that you can help me with that.
So here is a problem - I open a file and start reading but some how it is continue reading file even if it is empty. It is can not stop.
here is a code -
<?php
$flis = fopen ("users/".$IDN."/list.txt",'r');
$f= 1;
while (!feof($flis))
{
$CID = fgets ($flis, 99);
echo $f;
$f++;
}
fclose($flis);
?>
So I planing have a file with a lot of strings but it can not stop reading even an empty file, Please help me to find a mistake.
Also in while I planing to create a new block div . so here is a new question- how is better to create a div block? I use printf like that -
printf ("
<div id=\"message_contact\">
<a>
<div id=\"conto\">
</div>
</a>
</div>
");
But the problem is that the block will be a complex and plus it suppose to be a php function inside the block to put the information inside from database to that block. So can u recommend other methods to realize it?

Use foreach, Luke! And also file_get_contents and explode.
<?php
$path = 'users/' . $IDN . '/list.txt';
$contents = file_get_contents($path);
$lines = explode("\n", $contents);
?>
<div id="message_contact">
<?php
foreach ($lines as $line)
{
?>
<a>
<!-- DIV inside A? Okay! -->
<div id="conto">
<?php echo trim($line); ?>
</div>
</a>
<?php
}
?>
</div>
Note how I called trim() inside <div>. Poof, PHP inside HTML!

Edit, line by line
<?php
$flis = "users/".$IDN."/list.txt";
$fc = file_get_contents($fils);
$fca = explode("\n", $fc);
foreach ($fca as $line) {
echo $line;
// OR
include('template.php');
}
?>
template.php:
<div id="message_contact">
<a>
<div id="conto">
<?php echo $line; ?>
</div>
</a>
</div>
How's that?

Related

PHP file_get_contents(file.php); execute PHP code in file

I'm currently having an issue, where I have some php code in a file and calling that file from another file.
so:
index.php is calling file.php and file.php has some php code in it.
The reason I'm using file_get_contents, is that I have code in index.php that only needs to read some of the content in file.php, designated by tags. Based on teh section tag trigged by the ($_GET['identifier']); that section within the file.php is the only section displayed
Example code in file.php:
<?php
//simplified php code
var $item = "hello";
var $item2 = "Hola";
var $item3 = "おはよ";
?>
<section id="content">
<?php echo $item1; ?>
</section>
<section id="content2">
<?php echo $item2; ?>
</section>
<section id="content3">
<?php echo $item3; ?>
</section>
?>
code in index.php:
$content = file_get_contents('file.php');
if (isset($_GET['item'])) {
$section = $_GET['item'];
} else {
$section = 'content';
}
$delimiter = '<section id="' . $section . '">';
$start = explode($delimiter, $content);
$end = explode("</section>", $start[ 1 ] );
echo $end[0];
so if the browser url shows index.php?item=content2 , it should show the content from section ID named content2, along with the PHP code in that file, executed.
currently, if I do this, nothing is displayed, and a view source, show the php code
To execute the code before you get the contents, you either need to include and capture the output:
ob_start();
include('file.php');
$content = ob_get_clean();
Or get the file by URL (probably not the best idea and not portable):
$content = file_get_contents('http://example.com/file.php');

Using php file() function to put a html or php file into array

When I try to use the php file() function like:
in a test.php:
$lines = file("./folder/page.php");
foreach ($lines as $line ) {
echo $line;
}
page.php
<html>
<head>
<title></title>
</head>
<body>
<div class="about">
About:
</div>
<div class="question">
Question:
</div>
</body>
</html>
It returns,
About:
Question:
And no html tags, no php lines.
Goal, to have an array $lines with all the info as in the texteditor.
Your code works perfectly fine.
You are probably viewing your output on a browser which assumes that the HTML tags are a part of the page. If you view the page source you'll see that you get the desired output.
So escape your HTML characters you'll get your output just fine.
$lines = file("page.php");
foreach ($lines as $line ) {
echo htmlentities($line)."<br>";
}
In response to your what you asked me, try this:
$arrLines = array();
$lines = file("./folder/page.php");
foreach ($lines as $line ) {
$arrLines[] = $line;
}
var_dump($arrLines);

PHP replacing 'editable' areas in html files

I'm working on a tool to replace tagged areas in a html document. I've had a look at a few php template systems, but they are not really what I am looking for, so here is what I am after as the "engine" of the system. The template itself has no php and I'm searching the file for the keyword 'editable' to set the areas that are updatable. I don't want to use a database to store anything, instead read everything from the html file itself.
It still has a few areas to fix, but most importantly, I need the part where it iterates over the array of 'editable' regions and updates the template file.
Here is test.html (template file for testing purposes):
<html>
<font class="editable">
This is editable section 1
</font>
<br><br><hr><br>
<font class="editable">
This is editable section 2
</font>
</html>
I'd like to be able the update the 'editable' sections via a set of form textareas. This still needs a bit of work, but here is as far as I've got:
<?php
function g($string,$start,$end){
preg_match_all('/' . preg_quote($start, '/') . '(.*?)'. preg_quote($end, '/').'/i', $string, $m);
$out = array();
foreach($m[1] as $key => $value){
$type = explode('::',$value);
if(sizeof($type)>1){
if(!is_array($out[$type[0]]))
$out[$type[0]] = array();
$out[$type[0]][] = $type[1];
} else {
$out[] = $value;
}
}
return $out;
};
// GET FILES IN DIR
$directory="Templates/";
// create a handler to the directory
$dirhandler = opendir($directory);
// read all the files from directory
$i=0;
while ($file = readdir($dirhandler)) {
// if $file isn't this directory or its parent
//add to the $files array
if ($file != '.' && $file != '..')
{
$files[$i]=$file;
//echo $files[$i]."<br>";
$i++;
}
};
//echo $files[0];
?>
<div style="float:left; width:300px; height:100%; background-color:#252525; color:#cccccc;">
<form method="post" id="Form">
Choose a template:
<select>
<?php
// Dropdown of files in directory
foreach ($files as $file) {
echo "<option>".$file."</option>"; // do somemething to make this $file on selection. Refresh page and populate fields below with the editable areas of the $file html
};
?>
</select>
<br>
<hr>
Update these editable areas:<br>
<?php
$file = 'test.html'; // make this fed from form dropdown (list of files in $folder directory)
$html = file_get_contents($file);
$start = 'class="editable">';
$end = '<';
$oldText = g($html,$start,$end);
$i = 0;
foreach($oldText as $value){
echo '<textarea value="" style="width: 60px; height:20px;">'.$oldText[$i].'</textarea>'; // create a <textarea> that will update the editable area with changes
// something here
$i++;
};
// On submit, update all $oldText values in test.html with new values.
?>
<br><hr>
<input type="submit" name="save" value="Save"/>
</div>
<div style="float:left; width:300px;">
<?php include $file; // preview the file from dropdown. The editable areas should update when <textareas> are updated ?>
</div>
<div style="clear:both;"></div>
I know this answer is a little more involved, but I'd really appreciate any help.
Not sure if i correctly understand what you want to achieve. But it seems I would do that in jquery.
You can get all html elements that has the "editable" class like this :
$(".editable")
You can iterate on them with :
$(".editable").each(function(index){
alert($(this).text()); // or .html()
// etc... do your stuff
});
If you have all your data in a php array. You just need to pass it to the client using json. Use php print inside a javascript tag.
<?php
print "var phparray = " . json_encode($myphparray);
?>
I think it would be better to put the work on the client side (javascript). It will lower the server work load (PHP).
But as I said, I don't think I've grasped everything you wanted to achive.

Is it possible to add a <script> tag into HTML with PHP str_replace?

I have en exercise Im working on right now where we can't use libraries. I have a REST based system that instantiates different PHP classes depending on what needs to be done. I have several HTML files that are loaded into PHP and then using str_replace I switch out the variables I want to inject into the HTML.
I now want to add a tag at the end of one of my HTML files. My ../../html/body.html file looks like this:
<div id="content-wrapper">
<div id="content">
<table>
<!-- $content -->
</table>
</div>
</div>
</div>
<!-- javascript -->
</body>
</html>
I use this "body" page several times so the " $content " varies depending on what I replace them with in PHP.
Now for some reason when I try to replace javascript with a script tag it doesn't work. Heres my PHP that is trying to do this:
$javascript = '<script type="text/javascript" language="javascript" src="../../js/subscriber.js"></script>';
$page = file_get_contents("../../html/body.html");
$head = file_get_contents("../../html/doctype.html");
$nav = file_get_contents("../../html/Navbar.html");
$page = str_replace('<!--javascript -->', $javascript, $page);
$page = str_replace('<!-- $content -->', $theFeed, $page);
$nav = str_replace('<!-- $name -->', $this->user, $nav);
$nav = str_replace('$user', $this->you, $nav);
$nav = str_replace('$key', $this->key, $nav);
$nav = str_replace('$picUrl', $picUrl, $nav);
echo($head);
echo($nav);
echo($page);
I was thinking that this way I only need to include scripts on the necesarry pages or not at all if the page doesn't need any javascript. Does PHP or HTML block script tags somehow? Im not sure how to get around this. Thanks!
You're missing a space. Your markup contains:
<!-- javascript -->
^ space here
But your PHP code is missing that space:
$page = str_replace('<!--javascript -->', $javascript, $page);
Change it to:
$page = str_replace('<!-- javascript -->', $javascript, $page);
I think your problem is that in the PHP you have no space after

How can I keep an HTML snippet in a separate file, plug variables in as needed, and echo it out on demand?

For instance, let's say I have a snippet of code, which I'd like to keep separate. for now, we'll call it snippet.php.
snippet.php would be a simple block of reusable HTML which would have php variables in it. Something like this:
<article>
<h1>{$headline}</h1>
<p>${$body}</p>
</article>
I'd like to be able to return this code from a function, along the lines of this:
function writeArticle($headline, $body){
return "contents of snippet.php using the variables passed in to the function"
}
I know I could just use html in a string to return, but the actual snippet would be fairly complex, and I want it to be modular.
One method is using file_get_contents and str_replace
HTML:
<article>
<h1>[-HEADLINE-]</h1>
<p>[-BODY-]</p>
</article>
PHP:
function writeArticle($headline,$body){
$content = file_get_contents("[add your html directory here]/file.html",true);
$content = str_replace("[-HEADLINE-]",$headline,$content);
$content = str_replace("[-BODY-]",$body,$content);
echo $content;
}
You can use output buffering and include the file so the PHP variables get evaluated. However, since you are not using <?php PHP tags ?> you will need to wrap it in HEREDOC format (http://php.net/manual/en/language.types.string.php). Scroll down to Heredoc on the page.
snippet.php
$output = <<<HEREDOC
<article>
<h1>{$headline}</h1>
<p>{$body}</p>
</article>
HEREDOC;
function writeArticle($headline, $body){
ob_start();
include('snippet.php');
$snippet = ob_get_clean();
return $snippet
}
You could do this:
HTML DOCUMENT
Include('blockClass.php');
$block = new blockClass();
echo $bl = $block->block($headline, $body);
CLASS DOCUMENT
class blockClass{
function block($headline, $body){
$var ='<article>
<h1>' . $headline . '</h1>
<p>' . $body . '</p>
</article>';
return $var;
}
}
I had the same question and ended up solving it like this. I feel like this is the cleanest approach. Just turn php on and off within the function.
<?php
function writeArticle($headline, $body){
?>
<article>
<h1><?php echo $headline; ?></h1>
<p><?php echo $body; ?></p>
</article>
<?php
}
?>
writeArticle('foo', 'bar');

Categories