PHP replacing 'editable' areas in html files - php

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.

Related

Read all *.html files and add them to dropdown list as clickable (https) - PHP

I am working on a code that allows to read all the files in a directory with the HTML extension. These files are placed in a drop-down list. At that moment I have a piece of code that make it but I need a a little bit more.
There is the code:
<?php
$files = glob("archive/*.{html}", GLOB_BRACE);
echo '<select name="file">';
foreach($files as $file)
{
echo '<option>' . basename($file) . '</option>';
}
echo '</select>';
?>
I need the names in the list not to have the HTML extension and after click on it the HTML is open in the same tab. How to add full URL with ending as the name of HTML file:
"site.com/archive/" + "example.html" to open this file after click on it? And after reload the page to have the choosen option as shown on the list?
I am newbie in PHP and I struggle with it all the time.
Thank you in advance for any advices.
Pass each path as the <option>'s attribute value (example: /archive/lorem-ipsum.html). Note that it's the relative path to the vhost root, not necessarily to your PHP script.
Create a javascript event listener that listens on change of the <select> selected value.
Within the JS event listener, add a redirect (in this case I used location.href) to the desired value.
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<select name="file">
<option></option>
<?php
$files = glob("archive/*.{html}", GLOB_BRACE);
foreach($files as $file)
{
echo '<option value="/' . $file . '">' . basename($file) . '</option>';
}
?>
</select>
<script>
document.querySelector('select[name=file]').addEventListener('change', (event) => {
location.href = event.target.value;
});
</script>
</body>
</html>

How to make a textbox form redeem a promocode form a text file in php?

How to make a textbox form redeem a promo code form a text file in php i cant seem to figure it out it's for my csgo gambling site i want them redeem to redeem codes that comes from a text file /promo/codes.txt and make it so they can just use any codes from the list in the text file but im to useless :(
It depends totally on the format of the file.
Example:
ZQC01
ZQR92
ZQA84
ZQD73
To check if a promotion code is in this file and remove it afterwards:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$myPromoCode = isset($_POST['promocode']) ? $_POST['promocode'] : false;
$contents = file_get_contents('/path/to/file.txt');
$promoCodes = explode("\n", $contents);
// Check if the promo code is present in the file
if ($myPromoCode && in_array($myPromoCode, $promoCodes)) {
// Find the corresponding key
$key = array_search($myPromoCode, $promoCodes);
// Remove the code
unset($promoCodes[$key]);
// Write coes back to file
$contents = implode("\n", $promoCodes);
file_put_contents('/path/to/file.txt', $contents);
} else {
die("Promotion code doesn't exist");
}
}
?>
<form method="POST" action="<?= $_SERVER['PHP_SELF']; ?>">
<input type="text" name="promocode" />
<button type="submit">Redeem</button>
</form>

PHP link to include header

I have php reading a text file that contains all the names of images in a directory, it then strips the file extension and displays the file name without the .jpg extension as a link to let the user click on then name, what I am looking for is a easy way to have the link that is clicked be transferred to a variable or find a easier solution so the link once it is clicks opens a page that contains the default header and the image they selected without making hundreds of HTML files for each image in the directory.
my code is below I am a newbie at PHP so forgive my lack of knowledge.
thank you in advance. also I would like a apple device to read this so I want to say away from java script.
<html>
<head>
<title>Pictures</title>
</head>
<body>
<p>
<?php
// create an array to set page-level variables
$page = array();
$page['title'] = ' PHP';
/* once the file is imported, the variables set above will become available to it */
// include the page header
include('header.php');
?>
<center>
<?php
// loads page links
$x="0";
// readfile
// set file to read
$file = '\filelist.txt' or die('Could not open file!');
// read file into array
$data = file($file) or die('Could not read file!');
// loop through array and print each line
foreach ($data as $line) {
$page[$x]=$line;
$x++;
}
$x--;
for ($i = 0; $i <= $x; $i++)
{
$str=strlen($page[$i]);
$str=bcsub($str,6);
$strr=substr($page[$i],0,$str);
$link[$i]= "<a href=".$page[$i]."jpg>".$strr."</a>";
echo "<td>".$link[$i]."<br/";
}
?>
</P></center>
<?php
// include the page footer
include('/footer.php');
?>
</body>
</html>
add the filename to the url that you want to use as a landing page, and catch it using $_GET to build the link.
<a href='landingpage.php?file=<?php echo $filename; ?>'><?php echo $filename; ?></a>
Then for the image link on the landing page
<img src='path/to/file/<?php echo $_GET['file'] ?>.jpg' />

Simple HTML Parser issue

Hi so I'm trying to parse the ratemyprofessor website for professor name and comments and convert each div into plaintext. Here is the div class structure that I'm working with.
<div id="ratingTable">
<div class="ratingTableHeader"></div>
<div class="entry odd"><a name="18947089"></a>
<div class="date">
8/24/11 // the date which I want to parse
</div><div class="class"><p>
ENGL2323 // the class which I want to parse
</p></div><div class="rating"></div><div class="comment" style="width:350px;">
<!-- comment section -->
<p class="commentText"> // this is what I want to parse as plaintext for each entry
I have had Altimont for 4 classes. He is absolutely one of my favorite professors at St. Ed's. He's generous with his time, extremely knowledgeable, and such an all around great guy to know. Having class with him he would always have insightful comments on what we were reading, and he speaks with a lot of passion about literature. Just the best!
</p><div class="flagsIcons"></div></div>
<!-- closes comment -->
</div>
<!-- closes even or odd -->
<div class="entry even"></div> // these divs are the entries for each professor
<!-- closes even or odd -->
<div class="entry odd"></div>
<!-- closes even or odd -->
</div>
<!-- closes rating table -->
So every entry is encapsulated under this "ratingtable" div and each entry is either "entry odd" or "entry even" div.
Here is my attempt so far but it just produces a huge garbled array with a lot of garbage.
<?php
header('Content-type: text/html; charset=utf-8'); // this just makes sure encoding is right
include('simple_html_dom.php'); // the parser library
$html = file_get_html('http://www.ratemyprofessors.com/SelectTeacher.jsp?sid=834'); // the url for the teacher rating profile
//first attempt, rendered nothing though
foreach($html->find("div[class=commentText]") as $content){
echo $content.'<hr />';
}
foreach($html->find("div[class=commentText]") as $content){
$content = <div class="commentText"> // first_child() should be the <p>
echo $content->first_child().'<hr />';
//Get the <p>'s following the <div class="commentText">
$next = $content->next_sibling();
while ($next->tag == 'p') {
echo $next.'<hr />';
$next = $next->next_sibling();
}
}
?>
Confusing HTML... Could you try and see if this works?
foreach (DOM($html, '//div[#class="commentText"]//div[contains(#class,"entry")]') as $comment)
{
echo strval($comment);
}
Oh, and yeah - I don't like simple_html_dom, use this instead:
function DOM($html, $xpath = null, $key = null, $default = false)
{
if (is_string($html) === true)
{
$dom = new \DOMDocument();
if (libxml_use_internal_errors(true) === true)
{
libxml_clear_errors();
}
if (#$dom->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8')) === true)
{
return DOM(simplexml_import_dom($dom), $xpath, $key, $default);
}
}
else if (is_object($html) === true)
{
if (isset($xpath) === true)
{
$html = $html->xpath($xpath);
}
if (isset($key) === true)
{
if (is_array($key) !== true)
{
$key = explode('.', $key);
}
foreach ((array) $key as $value)
{
$html = (is_object($html) === true) ? get_object_vars($html) : $html;
if ((is_array($html) !== true) || (array_key_exists($value, $html) !== true))
{
return $default;
}
$html = $html[$value];
}
}
return $html;
}
return false;
}
If you still want to use simple_html_dom.. see below code for the mistakes in your code:
<?php
header('Content-type: text/html; charset=utf-8'); // this just makes sure encoding is right
include('simple_html_dom.php'); // the parser library
// you were trying to parse the wrong link.. your previous link did not have <div> tag with commentText class .. I chose a random link.. choose link for whichever professor you like or grab the links of professor from previous page store it in an array and loopr through them to get comments
$html = file_get_html('http://www.ratemyprofessors.com/ShowRatings.jsp?tid=1398302'); // the url for the teacher rating profile
//first attempt, rendered nothing though
//your div tag has class "comment" not "commentText"
foreach($html->find("div[class=comment]") as $content){
echo $content.'<hr />';
}
foreach($html->find("div[class=comment]") as $content){
// I am not sure what you are trying to do here but watever it is it's wrong
//$content = <div class='commentText'>"; // first_child() should be the <p>
//echo $content->first_child().'<hr />';
//correct way to do it
echo $html->firstChild();// ->first_child().'<hr />';
//this whole code does not make any sense since you are already retrieving the comments from the above code.. but if you still want to use it .. I can figure out what to do
//Get the <p>'s following the <div class="commentText">
// $next = $html->firstChild()->next_sibling();
// while ($next->tag == 'p') {
// echo $next.'<hr />';
// $next = $next->next_sibling();
// }
}
?>
Output
Comment
Dr.Alexander was the best. I would recommend him for American Experience or any class he teaches really. He is an amazing professor and one of the nicest most kind hearted people i've ever met.
Report this rating
Professor Alexander is SO great. I would recommend him to everyone for american experience. He has a huge heart and he's really interested in getting to know his students as actual people. The class isn't difficult and is super interesting. He's amazing.
Report this rating
Dins

Can PHP include work for only a specified portion of a file?

I have a PHP include that inserts an html form into another html form. When the form gets included I now have two form headers. Is there a php tag I could use that would allow me to...
<form id="orderform">
<!-- <?php for the include FROM here?> -->
PROD:<input class="ProductName" type="text" size="75">|
Discount:<input class="Discount" type="text" size="3">|
QTY:<input class="qty" type="text" size="6">|
Line/Total:<input class="LineTotal" type="text" size="9" disabled>
<!-- <?php for the include TO here?> -->
</form>
So the include would go into that file with the form in it and get the specified HTML?
Is this possible?
EDIT
<?php
$dom = new DOMDocument();
$html = 'phptest3.php';
$dom->loadHTMLFile($html);
$div = $dom->getElementById("divtagid");
echo $div->nodeValue;
?>
This only returns the text. How do I get the HTML form elements in the divtagid?
You should best look into php functions for this.
<?php
function form_tag_wrapper($form) {
return '<form id="orderform">'. $form .'</form>';
}
function form_contents() {
return 'PROD:<input class="ProductName" type="text" size="75">
...
Line/Total:<input class="LineTotal" type="text" size="9" disabled>';
}
?>
You will use this as:
$form = form_contents();
print form_tag_wrapper($form);
Or, as a oneliner:
print form_tag_wrapper(form_contents());
No, there isn't an alternate way to include a portion of a file. Consider: how would you describe to such a function where to start and end inclusion? How would the function know what you want?
As suggested, the best approach would be to refactor the included file. If that isn't an option (I can't imagine why it wouldn't be), another route is to use variables or constants in the included file to denote which portions should be output. Something like this:
#File: form_template.php
<?php if (!isset($include_form_header) || $include_form_header == true) { ?>
<form id="orderform">
<?php } ?>
PROD:<input class="ProductName" type="text" size="75">|
Discount:<input class="Discount" type="text" size="3">|
QTY:<input class="qty" type="text" size="6">|
Line/Total:<input class="LineTotal" type="text" size="9" disabled>
<?php if (!isset($include_form_header) || $include_form_header == true) { ?>
</form>
<?php } ?>
Now, when you want to stop the form header from being output:
$include_form_header = false;
include('form_template.php');
This is nasty, IMO. When someone else (or the future you) edits form_template.php, it may not be apparent when or why $include_form_header would be set. This kind of reliance on variables declared in external files can lead to spaghetti code.
You're far better building separate templates for different purposes (or directly echoing trivial output, like one line of html to open or close a form), for instance:
<?php
#File: order_form_wrapper.php
echo '<form id="orderform">';
?>
<?php
#File: product_fields.php
echo 'PROD:<input class="ProductName" type="text" size="75">';
echo 'Discount:<input class="Discount" type="text" size="3">';
echo 'QTY:<input class="qty" type="text" size="6">|';
echo 'Line/Total:<input class="LineTotal" type="text" size="9" disabled>';
?>
// form with wrapper
include 'order_form_wrapper.php';
include 'product_fields.php';
echo '</form>';
// different form with wrapper
include 'some_other_form_wrapper.php';
include 'product_fields.php';
include 'some_other_fields.php';
echo '</form>';
Last option, if you have absolutely no access to the template, can't modify it, can only include it, then you could use output buffering to include the file, load the resulting HTML into DOMDocument, then peal off the wrapping form tags. Take a look at the code... this isn't exactly "neat" either:
function extract_form_contents($template)
// enable output buffer, include file, get buffer contents & turn off buffer
ob_start();
include $template;
$form = ob_get_clean();
ob_end_clean();
// create a new DOMDocument & load the form HTML
$doc = new DOMDocument();
$doc->loadHTML($form);
// since we are working with an HTML fragment here, remove <!DOCTYPE, likewise remove <html><body></body></html>
$doc->removeChild($doc->firstChild);
$doc->replaceChild($doc->firstChild->firstChild->firstChild, $doc->firstChild);
// make a container for the extracted elements
$div = $doc->createElement('div');
// grab the form
$form = $doc->getElementsByTagName('form');
if ($form->length < 1)
return '';
$form = $form->item(0);
// loop the elements, clone, place in div
$nb = $form->childNodes->length;
if ($nb == 0)
return '';
for($pos=0; $pos<$nb; $pos++) {
$node = $form->childNodes->item($pos);
$div->appendChild($node->cloneNode(true));
}
// swap form for div
$doc->replaceChild($div, $form);
return $doc->saveHTML();
}
$contents = extract_form_contents('my_form_template.php');
You can structure your include file like an XML file with processing instructions­XML (DOMProcessingInstruction­Docs). Such a file would only miss the XML root element, which could be added on the fly.
The benefit of this is, that it is compatible with both XHTML and PHP as long as you write PHP with the standard tags like <?php ... ?> because those are a valid XML processing instruction. Let's start with a simple, XHTML only example, the principle with PHP code is actually the same, but why make it complicated?
include.php:
<form id="orderform">
Text: <input name="element" />
</form>
To create an include function that can deal with this, it only needs to parse the XML file and return the fragment in question, e.g. everything inside the <form> tag. XML parsing ships with PHP, so everything is already ready to action.
function incXML($file, $id = NULL)
{
if (!($xml = file_get_contents($file)))
throw new Exception('File IO error.');
$xml = '<template>' . $xml . '</template>';
$doc = new DOMDocument();
if (!$doc->loadXML($xml))
throw new InvalidArgumentException('Invalid file.');
// #todo add HTML namespace if you want to support it
// fetch the contents of the file however you need to,
// e.g. with an xpath query, I leave this for a training
// and just do a plastic getElementById here which does NOT
// work w/o proper DTD support, it's just for illustration.
if (NULL === $id)
{
$part = $doc;
}
else
{
if (!$part = $doc->getElementById($id))
throw new InvalidArgumentException('Invalid ID.');
}
$buffer = '';
foreach($part->childNodes as $node)
{
$buffer .= $doc->saveXML($node);
}
return 'data:text/html;base64,' . base64_encode($buffer);
}
Usage:
<?php
include(incXML('include.php', 'orderform'))
?>
You don't need to change any of your template files as long as they contain XHTML/PHP in the end with such a method.

Categories