It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I am using the template parser class in CodeIgniter to give the view (MVC) a designer-friendly look. I have a series of posts that I want to display, but on the front page I only want part of a post to show (first 200 characters) followed by a ... "Read More" link.
It is outputting the posts, but seems to be ignoring the PHP substr() function bc the text comes out full-length.
Inside the model class:
function __construct()
{
parent::__construct();
$this->load->library('parser');
$this->load->model('MPosts');
}
function index() // BASE_URL
{
$data = array("article_posts" => $this->MPosts->get_posts());
$this->parser->parse('VPosts', $data);
}
Inside the view:
<body>
{article_posts}
<h2>{title}</h2>
<p><?=substr("{post}", 0, 200);?>...</p>
<p>Read More</p>
<hr />
{/article_posts}
</body>
Since you are using a MySQL query to fetch the articles you can always use SUBSTRING(article_column_name,1,200) to only grab the first 200 chars, basically substr()
See: https://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_substring
Inside the parser->parse() code:
CI first passes your template through the load->view() processor, just like a regular view (so it executes PHP code inside your template),
then it passes it through the "{pseudovar}-replacer".
At this point I'm sure you understood the problem: substr() is applied to the string "{post}"
I can think of these options for your case:
do the substr() controller-side, probably the fastest solution to fix your issue
remove the Parser layer and use plain ol' PHP code, which is so fine
use a third-party über heavy full-featured template engine
Try echo instead of ?= .
People tend to leave code to load (model) libraries in constructors of the controller in which user-defined functions will invoke calls to user-defined functions implemented in model files.
Related
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I have a website I am making as a school project, and it appears I have jumped into something a bit too deep. I'm using PHP to create a page for each array object. In each page, I want to personalize the contents to match the page. For example, I have a page that gets created named Darryl and it's going to contain all my images. Other pages will be created and the contents of those pages will be created dynamically depending on the page.
What I am trying to do, is to change the img src using PHP and use a counter to make different images pop up. This is incredibly hard for me to explain.
I have this line of html code which contains the php(Which determines which images get shown:
<td><img style="width:11em;" class="magnify" src="<?php print $imgSrc; ?>"/><br><?php print $pageName; ?></td>
The part i am having issue with is the " print $imgSrc; " part. This is the area where my php will create the src path. It uses this variable $imgSrc to get the correct path.
That variable is:
$imgSrc = "images"."/".$pageName."/".counter();
Which writes the
It looks like you're confused about what a function is or perhaps when it gets executed. If this is all the code you have on your page:
$imgSrc = "images"."/".$pageName."/".counter();
<td>
<img style="width:11em;" class="magnify" src="<?php print $imgSrc; ?>"/><br>
<?php print $pageName; ?>
</td>
Then $imgSrc is only ever written to once. So whatever counter() does, it only does once. You could wrap the whole thing in a for loop and do away withe the counter() call. You could remove the local variable of $imageSrc and make the attribute defined on the fly, like so:
<td>
<img style="width:11em;" class="magnify" src="<?php print "images"."/".$pageName."/".counter(); ?>"/><br>
<?php print $pageName; ?>
</td>
Then if the counter() function is stateful itself (as in, it returns a different value each time you call it), you're all set.
You can make a stateful function like the following:
$counter_var = 0;
function counter() {
global $counter_var;
return $counter_var++;
}
But globals are frowned upon, because the create hard to trace side effects (and other reasons). Most people would tell you to use a for loop. I only mention it because it looks closer to what you were trying to do in your original code.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
Is it possible to search a remote page with a given URL for a given string, and indicate whether it exists, and if so, some indication of where it was found?
For instance, "Post Your Question" is included on this site https://stackoverflow.com/questions/ask.
In addition to searching just the page given by the URL, I would also like to search any JS or CSS links.
You can use the PHP Simple HTML DOM Parser to traverse through the contents of an html file.
Doing something like this:
$html = file_get_html('http://stackoverflow.com/questions/ask');
$htmlstring = $html->plaintext;
if(strstr($htmlstring, 'Post Your Question') === true)
// do your stuff here
Then to get the url to css or js:
foreach($html->find('link') as $css) {
$cssHref = $css->href;
//load the css, parse or whatever
}
foreach($html->find('script') as $script) {
$jsSrc = $script->src;
//load js, parse or whatever
}
From there you can grab the css or js source url and do what you want with it.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I'm creating a system like MVC.
I'm using below class when I want to call view files.
Edit: Meantime, He can do this: http://www.youtube.com/watch?feature=player_detailpage&v=Aw28-krO7ZM#t=1166s
<?php
class Call{
function __construct($fileName) {
//$this->db = new Database;
self::callFile($fileName);
}
function callFile($fileName)
{
$this->title = "example";
$this->description = "example";
$this->keywords = "example";
$fileName = $fileName . '.php';
require PAGESPATH.'common/header.php';
require PAGESPATH.$fileName;
require PAGESPATH.'common/footer.php';
}
}
?>
$fileName is index.php. Index.php has only
Index Page..
I want to print data in header.php like below:
<html>
<head>
<meta charset="utf-8">
<title><?php if(isset($this->title)){echo $this->title;} ?> - WebProgramlama.tk</title>
<meta name="description" content="<?php if(isset($this->description)){echo $this->description;}?>" />
<meta name="keywords" content="<?php if(isset($this->keywords)){echo $this->keywords;} ?>" />
</head>
<body>
But I'm getting errors.
Fatal error: Using $this when not in object context in /var/www/webprogramlama/class/pages/common/header.php on line 4
What can i solve this problem?
Note: Please be careful! header.php is calling by Call class. header.php is inside of Call class.
Edit: And Why this is running?
Stop watching that stupid "tutorial". It is so bad that at one point i actually begun to laugh.
You cannot just pick up a language, without any previous experience, and just start using high-level concepts. MVC is one of such concepts. To actually grasp it you need to understand object oriented programming and a lot of principles, that are associated with it.
Single Responsibility Principle
Separation of Concerns
Law of Demeter
Inversion of Control
Liskov Substitution Principle
.. etc. And you wont understand those principles just by reading the articles.
As for how to solve your problem, you could read this article. It will explain how to use templates. Which is actually what your "mvc tutorial" there actually is - bad guide for making routing mechanism and templates.
Also, you must understand that, if you do self::something();, it is outside an object. You are calling a static method on a class, which actually is just poor way of doing procedural programming.
You should start by learning the basics of OOP in PHP, because you don't get it. And for your own good, stay away from MVC and frameworks for a year at least.
Instead of calling the elements as $this->title outside the class, you need to create a new instance of the object in your code this like:
$callObject= new call($filename);
then refer to it in the page like this:
$callObject->title;
You can only use the $this-> code inside the class itself. Anywhere else, you need to make an object and therefore $this doesn't exist - the object of that class does - and you then have to refer to it by its name. At the same time, if your variable is going to be called $callObject you can't refer to it like that inside the class - as at that point you haven't made an instance of it, so you need to refer to it via the $this syntax which is a nice way of saying my element called title.
Edit: okay, I see what you are doing now, goodness me.
That's rather dangerous because your header.php file will contain loads of things that will only work inside the class called class - and generate hideous errors in every single other circumstance.
PHP will let you have the header.php file as it is, but as PHP evaluates the contents as it goes, your object is incomplete. You should have a read of this question which will answer that part in more detail.
Edit 2: Don't split a function between files.
If the code inside header.php is written be only used within the function (as it seems to be) copy the entire contents of it inside the class - and don't use a require or include to try to paste it in on the fly.
Never have more than one file for a class. It doesn't matter how long the file is.
Edit 3:
This is what your code should look like for the header section:
<?php
class Call{
function __construct($fileName) {
//$this->db = new Database;
self::callFile($fileName);
}
function callFile($fileName)
{
$this->title = "example";
$this->description = "example";
$this->keywords = "example";
$fileName = $fileName . '.php';
echo "
<html>
<head>
<meta charset='utf-8'>
<title>
";
echo (isset($this->title)) ? $this->title : "";
echo "
- WebProgramlama.tk</title>
<meta name='description' content='
";
echo (isset($this->description)) ? $this->description : "";
echo "' />
<meta name='keywords' content='
";
echo (isset($this->contents)) ? $this->contents : "";
echo "
' />
</head>
<body>
";
//require PAGESPATH.$fileName;
//require PAGESPATH.'common/footer.php';
// you can only include files that don't use any $this-> type elements.
}
}
?>
$this has no context outside of the class. Create an instance of your class and use that instead.
<html>
<head>
<meta charset="utf-8">
<?php
$class = new Call('filename');
?>
<title><?php if(isset($class->title)){echo $class->title;} ?> - WebProgramlama.tk</title>
<meta name="description" content="<?php if(isset($class->description)){echo $class->description;}?>" />
<meta name="keywords" content="<?php if(isset($class->keywords)){echo $class->keywords;} ?>" />
</head>
<body>
Get rid of your require statements in your callFile function; they have no place being there.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I have a problem with PHP and Javascript variable communication. I have this code:
<?php
$php_var = 'lol';
?>
<html>
<script type="text/javascript" charset="utf-8">
var php_var = "<?php echo $php_var; ?>";
alert(php_var);
</script>
</html>
This code does not work (as intended) for some reason. I cannot get the PHP variable's value passed down to Javascript variable. For some reason, Javascript completely ignores the php tags and assigns php_var a value of "". So it alerts the literal php code I put it as.
What am I doing wrong? I have been stuck on this problem for 3 hours. Is it my server's problem? (Using web hosting, dedicated). Thank you
Use json_encode() to ensure you get a valid JavaScript expression (otherwise characters such as newlines and quotes will break things):
var php_var = <?php echo json_encode($php_var); ?>;
You also need to ensure PHP is actually enabled for the file. This is usually achieved by giving the file a .php extension.
Use .php file extension and this will work.
If not then you variable won't have a value, you can see the exact issue by using something like firebug.
You say that the file where your code is located has an .html extension, it should be .php for it to render the php code.
Well, you can rename the file to .php and it should work or you can do the following thing:
Create a .htaccess file,
Add the following code ->
RewriteEngine On
<FilesMatch "(file.html)">
SetHandler php5-script
</FilesMatch>
save the file,
then in the html file add the following php line at the beggining ->
than you can write php code inside the selected html file
Or you can add the following rule
RewriteEngine On
file.html file.php
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 12 years ago.
PHP and HTML codes are all messed now in my application. What should I do? Something like template engine? I want to program it myself. It is with purpose to learn PHP.
Here's my view rendering function.
<?php defined('APPPATH') or die('no direct script access');
class ViewFileMissing extends Exception {}
function renderView($viewname, $data)
{
$filename = APPPATH.'/views/'.$viewname.'.php';
if (!file_exists($filename))
{
throw new ViewFileMissing($viewfile);
}
extract($data, EXTR_SKIP);
ob_start();
require($filename);
return ob_get_clean();
}
It can be used with a template like
<html>
<head>
<title><?php echo $title ?></title>
</head>
<body>
<p><?php echo $paragraph; ?></p>
</body>
</html>
It can then be called like
$data = array('title' => 'This is a title', 'paragraph' => 'This is a paragraph')
$html = renderView('viewname', $data)
It works by creating a local variable for each of the elements of the data array, turning on output buffering, requiring the template file, which outputs all of the html into the buffer and then clearing the buffer and returning the output. So all of the rendered html is now in a string that can be echoed.
The html is just for example, it wouldn't validate. Also note that this is the only legitimate use of extract that I have ever seen.
You could use MVC.
M - Models
Specifies the data to be shown and/or handled by the views and controllers.
V - Views
This is your actual HTML with the only PHP is the code that replaces itself with the data provided by the controller.
C - Controllers
Processes the browser's request, fetches the data from the model and passes it to the view.
Example
models/post.php - model - blog post (dummy data return, you could use a database, web service, whatever)
<?php
function post_with_id($id) {
$post = array();
$post["id"] = $id;
$post["title"] = "Sample post " . $id;
return $post;
}
post.php - controller - processes request, navigate to e.g. /post.php?id=3
<?php
require_once('models/post.php');
$post = post_with_id((int)$_GET["id"]);
include('views/post.php');
views/post.php
<h1><?php echo $post["title"]; ?></h1>
This really keeps your code clean. Just alter your model to fetch other data, from a database or from files for example and you have your dynamic content!
This is just a very simple example of MVC. Look at Wikipedia's article about it. Have fun!
Use MVC -- Model, View, Controller. Models contain application logic and database access, and overall data handling. Views contain HTML code and are like templates. Controllers are the URLs the user goes to, and include the models to retrieve/set the data and the views to display it.
Maybe look at some applications that use MVC and see how they're structured.
The simplest, and fastest, way to separate your presentation (HTML) from your logic (PHP) would be to use Smarty Templating Engine. It's a half-step between running hybrid files (where the logic and the presentation are mashed together) and a fuill MVC solution. But I would think that it would be easy to go that way, should you want to down the track.