Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 8 years ago.
Improve this question
I have a database field with large text. If there is a tag inside <!-- new page --> I want to paginate by that tag.
What I'm trying to do is something like WordPress has, when you insert a tag such as <!-- new page --> I want to create a new page.
Say I have this text from a database
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque elementum magna in nulla ultrices, eu pulvinar nulla auctor. Praesent auctor ut dui vitae feugiat.
<!-- new page -->
Sed risus nisl, tristique sed tristique et, auctor eu augue. In hac habitasse platea dictumst. Fusce a ipsum ligula. Aliquam vestibulum ligula ut ligula porta gravida. Curabitur tincidunt a est vitae eleifend. Duis ullamcorper nunc sapien, quis molestie tellus ornare vel. Nullam in mi eros.
How would I make the second paragraph appear on a new page?
Something like this http://en.support.wordpress.com/splitting-content/nextpage/
i hope my code will be helpfull :
<?php
//in this example :
//first you have to create a database with name : blog
// create table : article (id as primary key, name , content)
// here we supposed that in the content you have your tags <!-- new page -->
// also i supposed the name of this file as : pagination.php
//Getting the id of article:
//=========================
if(isset($_GET['id']))
$id_article = $_GET['id'];
else
$id_article = 1;
//Connexion to database :
//======================
$user="root";
$pass="root";
$db="blog";
$host="localhost";
$pdo_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
$bdd = new PDO('mysql:host='.$host.';dbname='.$db, $user, $pass, $pdo_options);
$bdd->query("SET NAMES 'utf8'");
$response = $bdd->query('SELECT * FROM articles WHERE id='.$id_article);
$tab_content = array();
$data = $response->fetch()
echo'<div >';
$tab_content = explode('<!-- new page -->',$data['content']);
$count_pages = count($tab_content);
if($count_pages){
//in the case that you have somme tags :
//=====================================
echo $tab_content[$page];
echo '<br>';
for($i=1;$i<$count_pages;$i++)
echo ''.$i.' ';
}
else{
//if no tags '<!-- new page -->' in your content:
//===============================================
echo $data['content'];
}
echo '</div>';
$response->closeCursor();
?>
Related
Hey i want to display some html/css depending on how many rows there are in database basically. Is there a way to do this without echo? Because i'm lost when i have to use many ' '. Here is code sample
<?php foreach ($result as $row) {
}?>
<div id="abox">
<div class="abox-top">
Order x
</div>
<div class="abox-panel">
<p>lorem ipsum</p>
</div>
<br>
<div class="abox-top">
lorem</div>
<div class="abox-panel">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut ac convallis diam, vitae rhoncus enim. Proin eu turpis at ligula posuere condimentum nec eu massa. Donec porta tellus ante, non semper risus sagittis at. Pellentesque sollicitudin sodales fringilla. Ut efficitur urna eget arcu luctus lobortis. Proin ut tellus non lacus dapibus vehicula non sit amet ante. Ut nibh justo, posuere sit amet fringilla eget, aliquam mattis urna.</p>
</div>
There's nothing complicated about it:
Simple/ugly:
<?php while($row = fetch()) { ?>
<div>
<?php echo $row['somefield'] ?>
</div>
<? } ?>
Alternative:
<?php
while ($row = fetch()) {
echo <<<EOL
<div>
{$row['somefield']}
</div>
EOL;
}
and then of course there's any number of templating systems, which claim to separate logic from display, and then litter the display with their OWN logic system anyways.
you can simply use <?= short opening tag introduced in php 5.3 before PHP 5.4.0 came out you had to enable short_open_tag ini but after 5.4.0 tag
here is an example
<?php $var='hello, world'; ?>
<?=$var ?> // outputs world
hope it helps.
Templates engines makes your life a pie
Take Smarty for example, it's pretty good template library. What template engine does is fetch variables to pre defined templates.
Your code in simple php:
<?php
echo 'My name is '. $name. ', that's why I'm awesome <br>';
foreach ($data as $value) {
echo $value['name'].' is awesome to!';
}
?>
Code in smarty:
My name is {$name}, that's why I'm awesome <br>
{foreach $data as $value}
{$value} is awesome to!
{/foreach}
Template engines pros:
Templates are held in separate custom named files. (i.e users.tpl, registration.tpl etc)
Smarty Caches your views (templates).
Simple to use i.e {$views + ($viewsToday/$ratio)}.
A lot of helpers.
You can create custom plugins/functions.
Easy to use and debug.
Most importantly: It separates your php code from html!
Template engines cons:
Sometimes hard to grip the concept of working for beginner.
Don't know any more actually
When I dont want to use a template engine (I like Twig, btw), I do something like this:
1) Write a separate file with the html code and some custom tags where data should be presented:
file "row_template.html":
<div class="abox-top">{{ TOP }}</div>
<div class="abox-panel"><p>{{ PANEL }}</p></div>
2) And then, read that file and do the replacements in the loop:
$row_template = file_get_contents('row_template.html');
foreach ($result as $row) {
$replaces = array(
'{{ TOP }}' => $row['top'],
'{{ PANEL }}' => $row['panel']
);
print str_replace(
array_keys($replaces),
array_values($replaces),
$row_template
);
}
In addition, you can change the content of "row_template.html" without touching the php code.
Clean and nice to the eye!
I have a really small webpage written in php (approx. 5 pages + blog entries). All pages are located in php files on the server side (no database is used). So far I managed to search inside my 'blog entries' - because these are just plain textfiles with HTML markup (I strip the tags & performing a search operation):
$file_name=array();
$search_string="";
if(isSet($_GET["query"])){
$search_string=$_GET["query"];
}
$search_result="";
$files="";
$phpfilename="";
$i=0;
if (!$search_string){
echo 'No query entered<br />';
}else{
if ($handle = opendir('content/')) {
while (false !== ($file = readdir($handle))){
if(strrchr($file, '.') === ".txt"){
$filename[]= $file;
}
}
closedir($handle);
}
foreach($filename as $value){
$files="content/$value";
$fp = strip_tags(file_get_contents($files));
if(stripos($fp, $search_string)) {
$search_result.=preg_replace('/<[^>]*>[^<]*<[^>]*>/', '', substr($fp,0,255)); // append a preview to search results
}
if($search_result!=""){
echo $search_result;
}else{
echo "No Results<br />";
}
}
}
Of course that works just because the files are plain text. But I've got also pages that are real 'php' files and want to perform a search operation on them too. But I don't want to search inside the 'php code' of course. I figured out, that I would need the preparsed files that the browser gets from the webserver - I thought about using file_get_contents() with http requests to all my pages (ok, 'just' about 5 pages but still)...
I've read here on SO that it's considered bad practice to do so and it feels like I'm taking the wrong approach.
Any ideas & suggestions would be highly appreciated.
Edit: A example for a regular page that I want to be able to search in
index.php
<?php ob_start(); require_once("./include/common.php"); ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title><?php echo $lang['WEBSITE_TITLE']; ?></title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<meta name="keywords" content="keyword, keyword, keyword" />
<link href="css/main.css" type="text/css" rel="stylesheet" />
</head>
<body>
<div id="page">
<!-- Header Area -->
<?php include("./include/header.php"); ?>
<?php include("./include/banner.php"); ?>
<div id="content">
<?php
$page = '';
if(isSet($_GET["page"])){
$page=$_GET["page"];
}
switch($page){
case 'category_1':
include("./include/category_1.php");
break;
case 'about':
include("./include/category_2.php");
break;
case 'contact':
include("./include/contact.php");
break;
default:
include("./include/home.php");
}
?>
<!-- /content --></div>
<!-- /page --></div>
<br />
<br /><br /><br />
<!-- Footer Area -->
<?php include("./include/footer.php"); ob_end_flush(); ?>
</body>
</html>
/include/category_1.php
<?php echo '<h2>'.$lang['NAVI_CAT_1'].'</h2>'; ?>
<div id="entry">
<br/>
<?php echo $lang['CAT_1_TEXT']; ?>
</div>
language file
<?php
$lang = array();
$lang['NAVI_CAT_1'] = 'Category 1';
$lang['CAT_1_TEXT'] = 'Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim.';
?>
Why not include into a buffer and then search the buffer's contents?
ob_start();
include ('index.php');
$contents = ob_get_clean();
//the $contents now includes whatever the php file outputs
I actually use this method in production code for all kinds of things, but mainly previewing site-generated emails before users send them. The nice thing is, you can use this on all the files, not just the php files.
this is failed by design.
consider not using plain mixed html sides. try to use xml files or wathever.
the alternative is crawling your own side. take a look at http://symfony.com/doc/current/components/dom_crawler.html
I create a simple backed area for my client to post new job openings and was wanting to give them the ability to format the text a little by adding line breaks in the job description text that will be visible on the front end.
The job openings are stored in a MySQL database.
Example of what I'm talking about:
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla quis quam sollicitudin, bibendum enim a, vulputate turpis.
Nullam urna purus, varius eget purus quis, facilisis lacinia nibh. Ut in blandit erat.
I've would like the breaks to happen when my client hits enter / return on the keyboard.
Any help on this matter would be appreciated.
------------UPDATE------------
okay so after much trial and error I got it somewhat working.
I added this line in my upload / action code.
$description = nl2br(htmlspecialchars($_POST['description']));
Full upload code is:
<?php
include($_SERVER['DOCUMENT_ROOT'] . "/connections/dbconnect.php");
$date = mysql_real_escape_string($_POST["date"]);
$title = mysql_real_escape_string($_POST["title"]);
$description = mysql_real_escape_string($_POST["description"]);
$description = nl2br(htmlspecialchars($_POST['description']));
// Insert record into database by executing the following query:
$sql="INSERT INTO hire (title, description, date) "."VALUES('$title','$description','$date')";
$retval = mysql_query($sql);
echo "The position was added to employment page.<br />
<a href='employment.php'>Post another position.</a><br />";
?>
Then on my form I added this to the textarea, but I get an error.
FYI that is line 80 the error is refering to.
Position Details:<br />
<textarea name="description" rows="8"><?php echo str_replace("<br />","",$description); ?></textarea>
</div>
Here is what the error looks like.
Here is my results page code:
<?php
$images = mysql_query("SELECT * FROM hire ORDER BY ID DESC LIMIT 10");
while ($image=mysql_fetch_array($images))
{
?>
<li data-id="id-<?=$image["id"] ?>">
<div class="box white-bg">
<h2 class="red3-tx"><?=$image["title"] ?> <span class="date-posted blue2-tx"><?=$image["date"] ?></span></h2>
<div class="dotline"></div>
<article class="blue3-tx"><?=$image["description"] ?><br />
<br />
For more information please call ###-###-####.</article>
</div>
</li>
<?php
}
?>
If I delete all that error copy and write out a real position with line breaks it works.
I have no idea how to fix the error though.
Again any help would be appreciated.
Thanks!
you can use str_replace
$statement = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla quis quam sollicitudin, bibendum enim a, vulputate turpis.
Nullam urna purus, varius eget purus quis, facilisis lacinia nibh. Ut in blandit erat."
$statement = str_replace(chr(13),"<br/>", $statement);
query example : INSERT INTO table (statement) VALUES ('$statement');
hope this can help you
EDIT :
if you want display the result at textarea from database u can using this code
$des = $row['description'] //my assumption that your feild name at table inside mySQL is description
Position Details:<br />
<textarea name="description" rows="8"><?php echo str_replace("<br />",chr(13),$des); ?></textarea>
</div>
hope this edit can help your second problem
I would start by answering a couple of questions first
Do I want my database to store html-formatted user input?
Is the data going to be editable afterwards?
Since you seem to want only nl2br, a simple approach would be to save the content as is in the database, then use nl2br() on the output side as Marcin Orlowski suggested.
Consider:
<?php
define('my_const', 100);
echo <<<MYECHO
<p>The value of my_const is {my_const}.</p>
MYECHO;
?>
If I put a variable inside the braces, it prints out. But not the constant. How can I do it?
You can also approach the problem by assigning the value of the constant to a variable.
Personally I do it that way because if you have lots of constants in your string then your sprintf() call can be quite messy. It's also then harder to scan through the string and see what is doing what. Plus, by assigning the variables individually, you can see what is taking on what value.
An example would be:
$const = CONST;
$variable = VARIABLE;
$foo = (new Foo)->setFooProperty(12)->getFooProperty();
$bar = (123 - 456) * 10;
$ten = 1 + 2 + 1 + (5 - 4);
<<<EOD
Lorem ipsum dolor sit amet, **$variable** adipiscing elit.
Duis gravida aliquet dolor quis gravida.
Nullam viverra urna a velit laoreet, et ultrices purus condimentum.
Ut risus tortor, facilisis sed porta eget, semper a augue.
Sed adipiscing erat non sapien commodo volutpat.
Vestibulum nec lectus sed elit dictum accumsan vel adipiscing libero.
**$const** vehicula molestie sapien.
Ut fermentum quis risus ut pellentesque.
Proin in dignissim erat, eget molestie lorem. Mauris pretium aliquam eleifend.
**$foo** vitae sagittis dolor, quis sollicitudin leo.
Etiam congue odio sit amet sodales aliquet.
Etiam elementum auctor tellus, quis pharetra leo congue at. Maecenas sit amet ultricies neque.
Nulla luctus enim libero, eget elementum tellus suscipit eu.
Suspendisse tincidunt arcu at arcu molestie, a consequat velit elementum.
Ut et libero purus. Sed et magna vel elit luctus rhoncus.
Praesent dapibus consectetur tortor, vel **$bar** mauris ultrices id.
Mauris pulvinar nulla vitae ligula iaculis ornare.
Praesent posuere scelerisque ligula, id tincidunt metus sodales congue.
Curabitur lectus urna, porta sed molestie ut, mollis vitae libero.
Vivamus vulputate congue **$ten**.
EOD;
Use sprintf()
define('my_const', 100);
$string = <<< heredoc
<p>The value of my_const is %s.</p>
heredoc;
$string = sprintf($string, my_const);
Here is an little trick to allow double-quoted strings and heredocs to contain arbitrary expressions in curly braces syntax, including constants and other function calls. It uses the fact that a function name can be assigned to a variable and then called within heredoc:
<?php
// Declare a simple function
function _placeholder($val) { return $val; }
// And assign it to something short and sweet
$_ = '_placeholder';
// Or optionally for php version >= 5.3
// Use a closure (anomynous function) like so:
$_ = function ($val){return $val;};
// Our test values
define('abc', 'def');
define('ghi', 3);
$a = 1;
$b = 2;
function add($a, $b) { return $a+$b; }
// Usage
echo "b4 {$_(1+2)} after\n"; // Outputs 'b4 3 after'
echo "b4 {$_(abc)} after\n"; // Outputs 'b4 def after'
echo "b4 {$_(add($a, $b)+ghi*2)} after\n"; // Outputs 'b4 9 after'
$text = <<<MYEND
Now the same in heredoc:
b4 {$_(1+2)} after
b4 {$_(abc)} after
b4 {$_(add($a, $b)+ghi*2)} after
MYEND;
echo $text;
You can also use the get_defined_constants function. It puts back all currently defined constants in an array, which you can use in your HEREDOC string:
// Let's say there is FOO and BAR defined
$const = get_defined_constants();
$meta = <<< EOF
my awesome string with "{$const['FOO']}" and "{$const['BAR']}" constants
EOF;
You may use the "constant" function.
for example:
<?php
define('CONST1', 100);
define('CONST2', 200);
$C= 'constant';
echo <<<MYECHO
<p>The value of CONST1 is: {$C('CONST1')},
and CONST2 is:{$C('CONST2')}.</p>
MYECHO;
?>
Put your defined variable into simple variable and use include it in heredoc just as in following example:
<?php
define('my_const', 100);
$variable = my_const;
echo <<<MYECHO
<p>The value of my_const is {$variable}.</p>
MYECHO;
?>
Not everybody will like the use of shorthand echo tags, but this is still an option:
<?php
define('my_const', 100);
?>
<p>The value of my_const is <?= my_const ?>.</p>
I am working with html document generated from Micrsoft Word 2007/2010. Besides generating incredibly dirty html, word also has the tendency of using both block and inline style. I am looking for a php library would merge block into already existing inline style element.
Edit
The goal is to construct a html block preserve the original formatting and editable in WYSIWYG editor like tinyMCE
Example
If the original html is:
<html>
<head>
<style>
.normaltext {color:black;font-weight:normal;font-size:10pt}
.important {color:red;font-weight:bold;font-size:11pt}
</style>
<body>
<p class="normaltext" style="font-family:arial">
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
In ut erat id dui mollis faucibus. Mauris eu neque et eros tempus placerat.
<span class="important">Nam in purus nisi</span>, vitae dictum ligula.
Morbi mattis eros eget diam vulputate imperdiet.
<span class="important" style="color:green">Integer</span> a metus eros.
Sed iaculis porta imperdiet.
</p>
</body>
</html>
Should become:
<html>
<head>
<body>
<p style="font-family:arial;color:black;font-weight:normal;font-size:10pt">
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
In ut erat id dui mollis faucibus. Mauris eu neque et eros tempus placerat.
<span style="color:red;font-weight:bold;font-size:11pt">Nam in purus nisi</span>, vitae dictum ligula.
Morbi mattis eros eget diam vulputate imperdiet.
<span style="color:green;font-weight:bold;font-size:11pt">Integer</span> a metus eros.
Sed iaculis porta imperdiet.
</p>
</body>
</html>
Check out:
http://inlinestyler.torchboxapps.com/
http://premailer.dialect.ca/
http://www.pelagodesign.com/sidecar/emogrifier/
http://blog.verkoyen.eu/blog/p/detail/convert-css-to-inline-styles-with-php
http://beaker.mailchimp.com/inline-css
http://burrowscode.wordpress.com/2011/02/19/emailify-internal-stylesheets-to-inline-styles/
https://github.com/crcn/emailify
https://github.com/peterbe/premailer
Porting code from either of the sources to PHP, or using any of the available APIs should do the trick of getting your CSS styling inline.
See the CssToInlineStyles project which does exactly what you want.
No, but try this instead, copying and pasting from word into http://ckeditor.com/ or tinymce, etc does clean it up A LOT, thought it's still not perfect it will get you much closer.
I finally managed to get it to work. The code is based off of
http://blog.verkoyen.eu/blog/p/detail/convert-css-to-inline-styles-with-php
with once simple change:
Moving the line
// add new properties into the list
foreach($rule['properties'] as $key => $value) $properties[$key] = $value;
up to the begining of the loop, right after where $properties is declared.
To make this work for WordPress however, one additional change is needed. DomDocument replace &nbps; from the document with blanks, which breaks WordPress update statement and lead to cotent being cut off. Please refer to my other question for the solution:
DOMDocument->saveHTML() converting to space
This problem is detailed in https://wordpress.stackexchange.com/questions/48692/post-content-getting-cut-off-on-blank-space-on-wpdb-update. If you know why this is happening for WordPress, please post your answer there as I would very much like to find out why it is happening.