How to check if text is present on a webpage? - php

how to check if text is present on a webpage using php and if true to execute some code?
My idea is to show some relevant products on the confirmation page after completing an order - if the name of the product is present on the page, then load some products. But I can't make the check for present text.

Case 1 if you prepare your page in a variable then echo it at the end of the script like
$response = "<html><body>";
$response .= "<div>contents text_to_find</div>";
$response .= "</body></html>";
echo $response;
then you can merely search the string with any string search function
if(strpos($response,"text_to_find") !==false){
//the page has the text , do what you want
}
Case 2 if you don't prepare the page in a string . and you just echo the contents and output the contents outside the <?php ?> tags like
<?php
//php stuff
?>
<HTML>
<body>
<?php
echo "<div>contents text_to_find</div>"
?>
</body>
</HTML>
Then you have no way to catch the text you want unless you use output buffering
Case 3 if you use output buffering - which I suggest - like
<?php
ob_start();
//php stuff
?>
<HTML>
<body>
<?php
echo "<div>contents text_to_find</div>"
?>
</body>
</HTML>
then you can search the output anytime you want
$response = ob_get_contents()
if(strpos($response,"text_to_find") !==false){
//the page has the text , do what you want
}

You may need to buffer your Output like so...
<?php
ob_start();
// ALL YOUR CODE HERE...
$output = ob_get_clean();
// CHECK FOR THE TEXT WITHIN THE $output.
if(stristr($output, $text)){
// LOGIC TO SHOW PRODUCTS WITH $text IN IT...
}
// FINAL RENDER:
echo $output;

Fastest solution is using php DOM parser:
$html = file_get_contents('http://domain.com/etc-etc-etc');
$dom = new DOMDocument;
$dom->loadHTML($html);
$divs = $dom->getElementsByTagName('div');
$txt = '';
foreach ($divs as $div) {
$txt .= $div->textContent;
}
This way, variable $txt would hold the text content of a given webpage, as long as it is enclosed around div tags, as usually. Good luck!

Related

Is it possible to have access to all the strings written before, on a page, with PHP?

Does PHP give access to all the strings that have been outputted to a page?
<html>
<body>
Link
<?php
echo 'hello world';
echo 'something else';
$s = get_all_output(); // does this exist ?
Of course I could replace every instance of echo 'some text'; by an initial $s = ''; and then $s .= 'some text';.
But without this trick, how to get the current page as a string?
You could make use of the output buffering of PHP (cf. https://www.php.net/manual/en/function.ob-get-contents.php).
<?php
ob_start(); // turn on buffering
echo "Hello ";
$out = ob_get_contents();
ob_end_clean(); // end buffering and clear buffer without "displaying it".
// process $out which contains "Hello "
echo "$out";
You must insert:
ob_start();
at the beginig of your php code and then
$s = ob_get_contents();
at the point where you want to get the content of the page.

PHP echo content from <tags>

I've searched around and around and I'm not sure how this really works.
I have the tags
<taghere>content</taghere>
and i want to pull the "content" so i can put an ifstatement depending on what the "content" is as the "content" is varrying depending on the page
i.e
<taghere>HelloWorld</taghere>
$content = //function that returns the text between <taghere> and </taghere>
if($content == "HelloWorld")
{
//execute function;
}
else if($content =="Bonjour")
{
//execute seperate function
}
i tried using preg but it doesnt seem to work and just returns whatever value is in the lines field instead of actually giving me the information within the tags
If I understand your question correctly, you want the data INSIDE the tag "taghere".
If you are parsing HTML, you should use DOMDocument
Try something similar to this:
<?php
// Assuming your content (the html where those tags are found) is available as $html
$doc = new DOMDocument();
libxml_use_internal_errors(true);
$doc->loadHTML($html); // loads your HTML
libxml_clear_errors();
// Note: Tag names are case sensitive
$text = $dom->getElementsByTagName('taghere');
// Echo the content
echo $text
you can use DomDocument and loadXML to do this
<?php
function doAction($word=""){
$html="<taghere>$word</taghere>";
$doc = new DOMDocument();
$doc->loadXML($html);
//discard white space
$hTwo= $doc->getElementsByTagName('taghere'); // here u use your desired tag
if($hTwo->item(0)->nodeValue== "HelloWorld")
{
echo "1";
}
else if($hTwo->item(0)->nodeValue== "Bonjour")
{
echo "2";
//execute seperate function
}
}
doAction($word="Bonjour");
You cannot do it like that. Technically it is possible but it's more than an overkill. And you mixed up PHP with HTML in a way that doesn't work.
To achieve the thing that you want you have to do something like this:
$content = 'something';
if ($comtent === 'something') {
//do something
}
if ($content === 'something else') {
//do something else
}
echo '<tag>'. $content . '</tag>' ;
Of course you can change $content in the ifs.
Dont forget, you can allways add an ID into a tag so you can reference it with java script.
<tag id='tagid'>blah blah blah </tag>
<script>
document.getElementById(tagid)
</script>
This might be a much simpler way to get what you are thinking about then some of the other responses
I don't know what regex you tried and therefor not what would have been wrong. Might have been the escaping of the <
<?php
if(preg_match('#\<taghere>(.*)\</taghere>#', $document, $a)){
$content = $a[1];
}
?>
I suppose there will be only one

How do I populate a variable using a function?

I have the code below on a page basically what I'm trying to do is fill $content variable using the function pagecontent. Anything inside pagecontent function should be added to the $content variable and then my theme system will take that $content and put it in theme. From the answers below it seems you guys think I want the html and php inside the actual function I don't.
This function below is for pagecontent and is what I'm currently trying to use to populate $content.
function pagecontent()
{
return $pagecontent;
}
<?php
//starts the pagecontent and anything inside should be inside the variable is what I want
$content = pagecontent() {
?>
I want anything is this area whether it be PHP or HTML added to $content using pagecontent() function above.
<?php
}///this ends pagecontent
echo functional($content, 'Home');
?>
I think you're looking for output buffering.
<?
// Start output buffering
ob_start();
?> Do all your text here
<? echo 'Or even PHP output ?>
And some more, including <b>HTML</b>
<?
// Get the buffered content into your variable
$content = ob_get_contents();
// Clear the buffer.
ob_get_clean();
// Feed $content to whatever template engine.
echo functional($content, 'Home');
As you are obviously a beginner here's a much simplified, working version to get you started.
function pageContent()
{
$html = '<h1>Added from pageContent function</h1>';
$html .= '<p>Funky eh?</p>';
return $html;
}
$content = pageContent();
echo $content;
The rest of the code you post is superfluous to your problem. Get the bare minimum working first then move on from there.
Way 1:
function page_content(){
ob_start(); ?>
<h1>Hello World!</h1>
<?php
$buffer = ob_get_contents();
ob_end_clean();
return $buffer;
}
$content .= page_content();
Way 2:
function page_content( & $content ){
ob_start(); ?>
<h1>Hello World!</h1>
<?php
$buffer = ob_get_contents();
ob_end_clean();
$content .= $buffer;
}
$content = '';
page_content( $content );
Way 3:
function echo_page_content( $name = 'John Doe' ){
return <<<END
<h1>Hello $name!</h1>
END;
}
echo_page_content( );

Storing an html page into a php variable [duplicate]

This question already has answers here:
HTML into PHP Variable (HTML outside PHP code)
(7 answers)
Closed 4 years ago.
Hi i'd like to store a dinamically generated(with php) html code into a variable and be able to send it as a reply to an ajax request.
Let's say i randomly generate a table like:
<?php
$c=count($services);
?>
<table>
<?php
for($i=0; $i<$c; $i++){
echo "<tr>";
echo "<td>".$services_global[$i][service] ."</td>";
echo "<td>".$services_global[$i][amount]."</td>";
echo "<td>€ ".$services_global[$i][unit_price].",00</td>";
echo "<td>€ ".$services_global[$i][service_price].",00</td>";
echo "<td>".$services_global[$i][service_vat].",00%</td>";
echo "</tr>";
}
?>
</table>
I need to store all the generated html code(and the rest) and echo it as a json encoded variable like:
$error='none';
$result = array('teh_html' => $html, 'error' => $error);
$result_json = json_encode($result);
echo $result_json;
I could maybe generate an html file and then read it with:
ob_start();
//all my php generation code and stuff
file_put_contents('./tmp/invoice.html', ob_get_contents());
$html = file_get_contents('./tmp/invoice.html');
But it sounds just wrong and since i don't really need to generate the code but only send it to my main page as a reply to an ajax request it would be a waste of resources.
Any suggestions?
You don't have to store it in a file, you can just use the proper output buffering function
// turn output buffering on
ob_start();
// normal output
echo "<h1>hello world!</h1>";
// store buffer to variable and turn output buffering offer
$html = ob_get_clean();
// recall the buffered content
echo $html; //=> <h1>hello world!</h1>
More about ob_get_clean()
if the data is so much expensive to regenerate then I would suggest you to use memcached.
Otherwise I would go regenerate it every-time or cache it on the frontend.
for($i=0;$i<=5;$i++)
{
ob_start();
$store_var = $store_var.getdata($i); // put here your recursive function name
ob_get_clean();
}
function getdata($i)
{
?>
<h1>
<?php
echo $i;
?>
</h1>
<?php
ob_get_contents();
}

How do I capture PHP output into a variable?

I'm generating a ton of XML that is to be passed to an API as a post variable when a user click on a form button. I also want to be able to show the user the XML before hand.
The code is sorta like the following in structure:
<?php
$lots of = "php";
?>
<xml>
<morexml>
<?php
while(){
?>
<somegeneratedxml>
<?php } ?>
<lastofthexml>
<?php ?>
<html>
<pre>
The XML for the user to preview
</pre>
<form>
<input id="xml" value="theXMLagain" />
</form>
</html>
My XML is being generated with a few while loops and stuff. It then needs to be shown in the two places (the preview and the form value).
My question is. How do I capture the generated XML in a variable or whatever so I only have to generate it once and then just print it out as apposed to generating it inside the preview and then again inside the form value?
<?php ob_start(); ?>
<xml/>
<?php $xml = ob_get_clean(); ?>
<input value="<?php echo $xml ?>" />͏͏͏͏͏͏
Put this at your start:
ob_start();
And to get the buffer back:
$value = ob_get_contents();
ob_end_clean();
See http://us2.php.net/manual/en/ref.outcontrol.php and the individual functions for more information.
It sounds like you want PHP Output Buffering
ob_start();
// make your XML file
$out1 = ob_get_contents();
//$out1 now contains your XML
Note that output buffering stops the output from being sent, until you "flush" it. See the Documentation for more info.
When using frequently, a little helper could be helpful:
class Helper
{
/**
* Capture output of a function with arguments and return it as a string.
*/
public static function captureOutput(callable $callback, ...$args): string
{
ob_start();
$callback(...$args);
$output = ob_get_contents();
ob_end_clean();
return $output;
}
}
You could try this:
<?php
$string = <<<XMLDoc
<?xml version='1.0'?>
<doc>
<title>XML Document</title>
<lotsofxml/>
<fruits>
XMLDoc;
$fruits = array('apple', 'banana', 'orange');
foreach($fruits as $fruit) {
$string .= "\n <fruit>".$fruit."</fruit>";
}
$string .= "\n </fruits>
</doc>";
?>
<html>
<!-- Show XML as HTML with entities; saves having to view source -->
<pre><?=str_replace("<", "<", str_replace(">", ">", $string))?></pre>
<textarea rows="8" cols="50"><?=$string?></textarea>
</html>

Categories