I'm stuck on how to write the test.php page result (after php has run) to a string:
testFunctions.php:
<?php
function htmlify($html, $format){
if ($format == "print"){
$html = str_replace("<", "<", $html);
$html = str_replace(">", ">", $html);
$html = str_replace(" ", " ", $html);
$html = nl2br($html);
return $html;
}
};
$input = <<<HTML
<div style="background color:#959595; width:400px;">
<br>
input <b>text</b>
<br>
</div>
HTML;
function content($input, $mode){
if ($mode =="display"){
return $input;
}
else if ($mode =="source"){
return htmlify($input, "print");
};
};
function pagePrint($page){
$a = array(
'file_get_contents' => array($page),
'htmlify' => array($page, "print")
);
foreach($a as $func=>$args){
$x = call_user_func_array($func, $args);
$page .= $x;
}
return $page;
};
$file = "test.php";
?>
test.php:
<?php include "testFunctions.php"; ?>
<br><hr>here is the rendered html:<hr>
<?php $a = content($input, "display"); echo $a; ?>
<br><hr>here is the source code:<hr>
<?php $a = content($input, "source"); echo $a; ?>
<br><hr>here is the source code of the entire page after the php has been executed:<hr>
<div style="margin-left:40px; background-color:#ebebeb;">
<?php $a = pagePrint($file); echo $a; ?>
</div>
I'd like to keep all the php in the testFunctions.php file, so I can place simple function calls into templates for html emails.
Thanks!
You can use output buffering to capture the output of an included file and assign it to variable:
function pagePrint($page, array $args){
extract($args, EXTR_SKIP);
ob_start();
include $page;
$html = ob_get_clean();
return $html;
}
pagePrint("test.php", array("myvar" => "some value");
And with test.php
<h1><?php echo $myvar; ?></h1>
Would output:
<h1>some value</h1>
This may not be exactly what you're looking for but it seems you want to build an engine of sorts for processing email templates into which you can put php functions? You might check out http://phpsavant.com/ which is a simple template engine that will let you put in php functions directly into a template file as well as basic variable assignment.
I'm not sure what printPage is supposed to be doing but I would re-write it like this just to make it more obvious because the array of function calls is a bit complicated and I think this is all that is really happening:
function pagePrint($page) {
$contents = file_get_contents($page);
return $page . htmlify($contents,'print');
};
and you might consider getting rid of htmlify() function and use either of the built-in functions htmlentities() or htmlspecialchars()
Seems like my original method may not have been the best way of going about it. Instead of posing a new question on the same topic, figured it was better to offer an alternate method and see if it leads to the solution I am after.
testFunctions.php:
$content1 = "WHOA!";
$content2 = "HEY!";
$file = "test.html";
$o = file_get_contents('test.html');
$o = ".$o.";
echo $o;
?>
text.php:
<hr>this should say "WHOA!":<hr>
$content1
<br><hr>this should say "HEY!":<hr>
$content2
I'm basically trying to get $o to return a string of the test.php file, but I want the php variables to be parsed. as if it was read like this:
$o = "
<html>$content1</html>
";
or
$o = <<<HTML
<html>$content1</html>
HTML;
Thanks!
Related
Using PHP how to comment in all php code inside certain php file
for example if i've the followig file
$file = 'myfile.php';
has only PHP code
<?php
$c = 'anything';
echo $c;
?>
I want using PHP to comment in (add /* just after open tag <?php and */ just before close tag ?>) to be
<?php
/*
$c = 'anything';
echo $c;
*/
?>
And also how to do the reverse bycomment out (remove /* */) to return back to
<?php
$c = 'anything';
echo $c;
?>
I've been thinking to use array_splice then doing str_replace then using implode and file_put_contents but still unable to figure out how to do this.
Update
Okay meanwhile getting some help over here, i was thinking about it and it comes to my mind this idea .... USING ARRAY!
to add block comment /* just after open tag <?php i will convert the content of that file into array
$contents = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
and then i can array push new element at position 2 with /*
and to do the reverse i will use unset($contents[1]); to unset element at postion 2 which means, /* will be gone
later on i can file_put_contents($file, $contents); to re-write the file again.
You can use PREG_REPLACE :
<?php
function uncomment($file_path) {
$current = file_get_contents($file_path);
$current = preg_replace('/\\/\\*(.+?)\\*\\//s', '$1', $current);
file_put_contents($file_path, $current);
return $current;
}
echo "<plaintext>" . uncomment("code.php");
?>
BEFORE :
AFTER :
I don't know why you want comment or uncomment the php code but I don't think it's a good way to do. I advice you to use variable or constant, like this :
One other way to enable or disable you code, is to use constant variable after the second time :
TOGGLE/UNTOGGLE COMMENT :
You will be able to do :
uncomment("code.php", "MYENV_DEBUG"); // uncomment
uncomment("code.php", "MYENV_DEBUG"); // comment
uncomment("code.php", "MYENV_DEBUG"); // uncomment
uncomment("code.php", "MYENV_DEBUG"); // comment
FIRST TIME :
SECOND TIME :
THIRD TIME :
Code :
<?php
function uncomment_header($name, $value) {
return '<?php define("' . $name . '", ' . $value . '); ?>';
}
function uncomment($file_path, $name) {
$current = file_get_contents($file_path);
$regex = '/<\\?php define\\("' . $name . '", (0|1)\\); \\?>/';
if (preg_match($regex, $current, $match)) {
$value = ($match[1] == 1) ? 0 : 1;
$current = preg_replace($regex, uncomment_header($name, $value), $current);
} else {
$header = uncomment_header($name, 1) . "\n";
$start = 'if (' . $name . '):';
$end = 'endif;';
$current = $header . $current;
$current = preg_replace('/\\/\\*(.+?)\\*\\//s', $start . '$1' . $end, $current);
}
file_put_contents($file_path, $current);
return $current;
}
echo "<plaintext>" . uncomment("code.php", "MYENV_DEBUG");
?>
There are two types of comments in PHP 1)single line comment 2)Multiple line comment for single comment in php we just type // or # all text to the right will be ignored by PHP interpreter. for example
<?php
echo "code in PHP!"; // This will print out Hello World!
?>
Result: code in PHP!
For multiple line comments multiple line PHP comment begins with " /* " and ends with " / " for example
<?php
/* This Echo statement will print out my message to the
the place in which I reside on. In other words, the World. */
echo "Hello World!";
/* echo "My name is Noman Ali!";
echo "PHP Programmer!";
*/?>
Result: Hello World!
Like this:
#canned test data, a string and the file contents are the same
$contents = <<<'CODE'
<?php
$c = 'anything';
echo $c;
?>
CODE;
$contents = preg_replace(['/<\?php\s/','/\?\>/'], ['<?php/*', '*/?>'], $contents);
echo $contents;
Output
<?php/*
$c = 'anything';
echo $c;
*/?>
Sandbox
NOTE - this will only work if the ending tag is present. In PHP the ending tag is actually optional. This will also not work on things like short tags <? or <?= although it will catch the ending tags.
Because of these edge cases it's very hard to do with regex (or any string replacement).
Valid examples of PHP code
<?php
$c = 'anything';
echo $c;
?>
//-------- no ending tag ---------
<?php
$c = 'anything';
echo $c;
//------- short tags ---------
<? echo 'foo'; ?>
//------- short echo tags ---------
<?= $foo; ?>
etc...
Good luck if you want to try to catch them all....
I'm new to PHP and I come from Objective-C. I need to create a plugin for WP that returns an HTML table where each row is populated by data from JSON. In essence, as an example, I need to replace echo with return:
$jsonurl = "http://xxxx/club/api/xxxx/category/";
$json = file_get_contents($jsonurl,0,null,null);
$json_output = json_decode($json);
//print_r ($json_output);
echo "<table>";
foreach ( $json_output->result as $result )
{
echo "<tr><td>".$result->id."</td><td>".$result->categoryKind."</td><td>".$result->ranking."</td>";
}
echo "</table>" ;
That works! I can see output as expected. But for showing table in WP through Shortcode, I need return and no echo. So how can I replace the echo with return?
I tried:
function foobar_func(){
$html= "<table>";
foreach ( $json_output->result as $result )
{
$html. = "<tr><td>".$result->id."</td><td>".$result->categoryKind."</td><td>".$result->ranking."</td>";
}
$html. = "</table>" ;
return $html;
}
add_shortcode( 'foobar', 'foobar_func' );
without success. Any help is welcome.
UPDATE: Same result (no work). I will exit crazy.
function foobar_func($json_output){
$html= "<table>";
foreach ( $json_output->result as $result )
{
$html. = "<tr><td>".$result->id."</td><td>".$result->categoryKond."</td> <td>".$result->ranking."</td>";
}
$html. = "</table>" ;
return $html;
}
add_shortcode( 'foobar', 'foobar_func' );
please try ob_start() method i think it useful to you.
http://php.net/manual/en/function.ob-start.php
<?php
function callback($buffer)
{
// replace all the apples with oranges
return (str_replace("apples", "oranges", $buffer));
}
ob_start("callback");
?>
<html>
<body>
<p>It's like comparing apples to oranges.</p>
</body>
</html>
<?php
ob_end_flush();
?>
Variable scope is your problem here. $json_output isn't accessible within the function.
Change to the following:
function foobar_func(){
global $json_output;
$html= "<table>";
Alternatively to calling it as a global variable, you can pass it within the function call.
function foobar_func($json_output){
And then when you call the function, use foobar_func($json_output)
After investigating I found the way out. But honestly I can't understand why this code works. Thank you all for putting me on the right path.
Code:
function foobar_func($json_output){
$jsonurl = "http://xxxx/club/api/xxx/category/";
$json = file_get_contents($jsonurl,0,null,null);
$json_output = json_decode($json);
echo "<table>";
foreach ( $json_output->result as $result )
{
echo "<tr><td>".$result->id."</td><td>".$result->categoryKind."</td><td>".$result->ranking."</td>";
}
echo "</table>" ;
return $html;
}
add_shortcode( 'foobar', 'foobar_func' );
i wrote simple 3 functions to scrape titles , description and keywords of simple html page
this is the first function to scrape titles
function getPageTitle ($url)
{
$content = $url;
if (eregi("<title>(.*)</title>", $content, $array)) {
$title = $array[1];
return $title;
}
}
and it works fine
and those are 2 functions to scrape description and keywords and those not working
function getPageKeywords($url)
{
$content = $url;
if ( preg_match('/<meta[\s]+[^>]*?name[\s]?=[\s\"\']+keywords[\s\"\']+content[\s]?=[\s\"\']+(.*?)[\"\']+.*?>/i', $content, $array)) {
$keywords = $array[1];
return $keywords;
}
}
function getPageDesc($url)
{
$content = $url;
if ( preg_match('/<meta[\s]+[^>]*?name[\s]?=[\s\"\']+description[\s\"\']+content[\s]?=[\s\"\']+(.*?)[\"\']+.*?>/i', $content, $array)) {
$desc = $array[1];
return $desc;
}
}
i know there may be something wrong with the preg_match line but i really don't know
i tried it so much things but it doesn't work
Why not use get_meta_tags? PHP Documentation Here
<?php
// Assuming the above tags are at www.example.com
$tags = get_meta_tags('http://www.example.com/');
// Notice how the keys are all lowercase now, and
// how . was replaced by _ in the key.
echo $tags['author']; // name
echo $tags['keywords']; // php documentation
echo $tags['description']; // a php manual
echo $tags['geo_position']; // 49.33;-86.59
?>
NOTE You can change the parameter to either a URL, local file or string.
Its better to use php's native DOMDocument to parse HTML then regex, you can also use , tho in this day in age allot of sites dont even add the keywords, description tags no more, so you cant rely on them always being there. But here is how you can do it with DOMDocument:
<?php
$source = file_get_contents('http://php.net');
$dom = new DOMDocument("1.0","UTF-8");
#$dom->loadHTML($source);
$dom->preserveWhiteSpace = false;
//Get Title
$title = $dom->getElementsByTagName('title')->item(0)->nodeValue;
$description = '';
$keywords = '';
foreach($dom->getElementsByTagName('meta') as $metas) {
if($metas->getAttribute('name') =='description'){ $description = $metas->getAttribute('content'); }
if($metas->getAttribute('name') =='keywords'){ $keywords = $metas->getAttribute('content'); }
}
print_r($title);
print_r($description);
print_r($keywords);
?>
Why won't my script return the div with the id of "pp-featured"?
<?php
# create and load the HTML
include('lib/simple_html_dom.php');
$html = new simple_html_dom();
$html->load("http://maps.google.com/maps/place?cid=6703996311168776503&q=hills+garage&hl=en&view=feature&mcsrc=google_reviews&num=20&start=0&ved=0CFUQtQU&sa=X&ei=sCq_Tr3mJZToygTOmuCGCg");
$ret = $html->find('div[id=pp-featured]');
# output it!
echo $ret->save();
?>
this gets me on my way. Thanks for your help.
<?php
include_once 'lib/simple_html_dom.php';
$url = "http://maps.google.com/maps/place?cid=6703996311168776503&q=hills+garage&hl=en&view=feature&mcsrc=google_reviews&num=20&start=0&ved=0CFUQtQU&sa=X&ei=sCq_Tr3mJZToygTOmuCGCg";
$html = file_get_html($url);
$ret = $html->find('div[id=pp-reviews]');
foreach($ret as $story)
echo $story;
?>
The library always returns an array because it may be possible that more than one item matches the selector.
If you expect only one you should check to ensure the page your analyzing is behaving as expected.
Suggested solution:
<?php
include_once 'lib/simple_html_dom.php';
$url = "http://maps.google.com/maps/place?cid=6703996311168776503&q=hills+garage&hl=en&view=feature&mcsrc=google_reviews&num=20&start=0&ved=0CFUQtQU&sa=X&ei=sCq_Tr3mJZToygTOmuCGCg";
$html = file_get_html($url);
$ret = $html->find('div[id=pp-reviews]');
if(count($ret)==1){
echo $ret[0]->save();
}
else{
echo "Something went wrong";
}
I'm using the following function to open a file:
function example() {
$foo = fopen('file.txt', 'r');
while (!feof($foo)) {
$foo2 = fgets($foo);
echo $foo2;
}
}
Here's the code where it's called:
<?php
include($_SERVER['DOCUMENT_ROOT']."/class_lib.php");
$page = new Page();
function example() {
$foo = fopen('file.txt', 'r');
while (!feof($foo)) {
$foo2 = fgets($foo);
echo $foo2;
}
}
$page->meta = array
(
'title' => 'snip',
'description' => 'snip'
);
$page->content = "
snipsnipsnipsnipsnipsnip
<div id=\"foo\">
<pre>
".example()."
</pre>
</div>
<br/>snipsnip
";
$page->Display();
?>
For some reason, even though the function is called within the pre element, it appears at the start of the page (the file is output, then the html is loaded). Same thing happens when I use include(). I must overlooking something obvious... any ideas?
Here's the class_lib.php if it's needed: http://pastebin.com/7euqEWNq
You use echo when reading your file, so it's directly printed out.
You can used output buffering : ob_start
Or simply get the file content and use it instead or you function call : file_get_contents
What you should to is let the example method return a value as the result and than echo that at the position you are calling it from. Like so:
function example() {
$foo = fopen('file.txt', 'r');
while (!feof($foo)) {
$foo2 = fgets($foo);
return $foo2;
}
}
$exampleData = example();
$page->content = "snipsnipsnipsnipsnipsnip
<div id=\"foo\">
<pre>".$exampleData."</pre>
</div>
<br/>snipsnip";
I guess that's because your echo sentence, the first thing to be sent to the browser is the echo sentence output, so it shows first no matter where you place it.
You should return not echo, something like this:
function example() {
$output = '';
$foo = fopen('file.txt', 'r');
while (!feof($foo)) {
$foo2 = fgets($foo);
$output .= $foo2;
}
return $output;
}