echo content data from url source - php

Hey guys I'm not too knowledgeable about this particular topic in PHP yet. Basically I wanted to get a certain content of the url source so for instance the code below will only echo that specific content from the source page. I wanted to do this for other websites and the script below has errors but that's just like a demo of what I want to accomplished.
<?php
$data = file_get_contents('http://www.jokesclean.com/OneLiner/Random/');
$data = getBetween($data,'<p class="c"> <font size="+2">',"</font></p>");
echo $data;
?>
All the information of the script above is located here

Use Simple HTML DOM to do this.
Read the manual to do this from here.
Its pretty simple.
//include simple_html_dom.php file.
include('../simple_html_dom.php');
// get DOM from URL or file
$html = file_get_html('http://www.jokesclean.com/OneLiner/Random/');
foreach($html->find('p[class=c]') as $e)
echo $e;
Just tested on my local system and it worked perfectly generating a random joke everytime i refresh
here's what i got on last refresh of this code.
.

It'd be best to use domdocument but you can also do it using regular expressions like the following.
$data = file_get_contents('http://www.jokesclean.com/OneLiner/Random/');
if ( preg_match('/\<font size="\+2"\>(.*?)\<\/font\>/', $data, $match) ) {
echo $match['1'];
}
else {
echo 'couldn\'t find a match';
}

Related

Using html code in php function or no?

i would to know what is good practice for writing code to put all HTML code inside PHP function and in my front index.php file just call function to show code.
class.php:
public function test() {
$sql='select id,title from test ';
$nem=$this->db->prepare($sql);
$nem->execute();
$nem->bind_result($id,$title);
echo '<ul class="centreList">';
while($nem->fetch())
{
echo '<li>'.$id.'<a href="'.$title.'" >Download</a></li>';
}
echo '</ul>';
}
index.php:
<?php $connection->test(); ?>
This work fine, but I would like to know is this proper way or is not a good practice to use html code inside PHP functions?
It's ok to build HTML within PHP, but I would not echo to the screen directly from within the function. Instead, return the built HTML string.
$html = '<ul class="centreList">';
while($nem->fetch())
{
$html .= '<li>'.$id.'<a href="'.$title.'" >Download</a></li>';
}
$html .='</ul>';
return $html
The function should not be responsible for pushing content to the browser because it really limits what you can do with your code. What if you wanted to further process the HTML? What if you run into a condition later in the code and decided to abort? What if you wanted to set some response headers later? Some content would already be gone so none of these things would be possible without clever workarounds.
In general you want to separate your responsibilities: I would even break things down further:
one piece of code is in charge of retrieving info from the DB and returning
Another piece is in charge of building the HTML string
A third piece is in charge of displaying the HTML (probably your index.php)
New index.php
<?= $connection->test(); ?>
Do not use echo to print the html directly, wrap the html within while loop surrounded by php tags
public function test() {
$sql='select id,title from test ';
$nem=$this->db->prepare($sql);
$nem->execute();
$nem->bind_result($id,$title);
return $nem;
}
<ul class="centreList">
<?php $res = test()->fetch();
while( $res->fetch() ) { ?>
<li> <?php echo $id ?> Download </li>;
<?php } ?>
</ul>

Simple Snippet to read and show content from file

I am looking for a simple solution to add a Snippet in my index.php file to load and display the content shown in a file from an other Domain.
Plan was to add the Code to the 'Footer' before to show a floating ad on several of my websites.
Sourcesite: http://domainX.tld/floating/floater.txt
Content of file: little bit css for styling of the ad + script snippet for a close button + html to get it into shape.
Target Site gets a simple snippet to show content from txt file as its own content.
I have tried by now
<?php
$StrLessDescription = ("//domainX.tld/floating/floater.txt");
$file_contents = file_get_contents($StrLessDescription);
?>
Site loads but doen't shows anything of my code.
<?php
$handle = fopen("//domainX.tld/floating/floater.txt", "rb");
$delimiter = ",";
while (!feof($handle) ) {
$line = fgets($handle);
$data = explode($delimiter, $line);
foreach($data as $v) {
echo $v;
}
}
fclose($handle);
?>
Site wouldn't even load.
<?php
$f = fopen("//domain.tld/floating/floatr.txt", "r");
// Read line by line until end of file
while(!feof($f)) {
echo fgets($f) . "<br />";
}
fclose($f);
?>
Creates an endless amount of where my Code should be
Other Fails i have deleted already.
Once i had a simple snippet that had done the trick, does one have any idea how to accomplish that again?
This should do the trick:
<?php
echo file_get_contents('//domain.tld/floating/floatr.txt');
Sticking to the straightest way to do it as your intention is and supposing that:
URL you provide for the txt file is correct
you have read access to it
the file has contents to display
your PHP version is (PHP 4 >= 4.3.0, PHP 5, PHP 7) to support
the file_get_contents() function
You are missing in your first approach to echo the contents of your variable $StrLessDescription to send it to output.
<?php
$StrLessDescription = ("//domainX.tld/floating/floater.txt");
$file_contents = file_get_contents($StrLessDescription);
echo $file_contents;
?>
Remember that for large projects you could consider using a framework to achieve the same goal in a more organized way. This is a solution to a quick-and-dirty approach you inquiry.

php with preg_match_all() generates no results

I'm trying to use this php script in order to locate a stock quote from yahoo finance. The problem I'm having is that when the script is run it generates no results. This leads me to believe that my regular expression is incorrect, but when I use the same regex on myregextester.com it shows the results that I expect with the given input. Any help will be greatly appreciated. Also, my php may be incorrect for what I'm trying to do.
<html>
<head>
<title>Stock Quote from Nasdaq</title>
</head>
<body>
<?php
// choose stock to look at
$symbol = 'AMZN';
echo "<h1> Stock Quote for $symbol </h1>";
//echo 'this printed (1)<br />';
$theurl = 'http://finance.yahoo.com/q?s=AMZN';
//echo 'this printed (2)<br />';
$contents = file_get_contents($theurl);
//find the part of the page we want and output it
if (preg_match_all('/amzn">([0-9]+\.[0-9]+)/', $contents, $matches)) {
echo "The price for $symbol: ".$matches[1][0];
} else {
echo "No Results";
}
?>
</body>
</html>
What you are searching for is:
<span id="yfs_l10_amzn">221.37</span>
Your regex would succeed for that.
So your actual problem is retrieving the page. Besides the obnoxious $theurl variable name, you should just use file_get_contents instead of fread etc.
$contents = file_get_contents($theurl);
Worked in your snippet.
I just downloaded the url http://finance.yahoo.com/q?s=AMZN and looked at the page source. Done a seach for /amzn. One match. That was <a href="/marketpulse/AMZN">Market Pul.... Hence no match.
Need to have a rethink.
Escape the >
try this:
preg_match_all('/amzn"\>[0-9]+\.[0-9]+/',$contents, $matches);

PHP Check if page contains

I'm looking for a quick code/function that will detect if a page contains a certain thing.
It's for a new project I'm working on.
Basically, the user will paste a simple javascript code into their pages, but I need to make sure they do.
I need a code that will scan through a specific webpage url and find the code I provided.
Thanks!
You want to scan through a webpage, not an URL! You get to the webpage through an URL. :)
<?php
$contents = file_get_contents("http://some.site/page.html");
$search = <<<EOF
<script type="text/javascript">
alert('They must have this!');
</script>
EOF;
if (strpos($contents, $search) === FALSE) {
echo "Naughty webpage!";
}
?>
Note, though, that programmatically skimming pages like this is generally considered bad form.
You can get the contents of a URL as a string, and search the contents for that code:
<?php
function check_url($url) {
$page = file_get_contents($url);
$code = '<script src="http://example.com/test.js"></script>';
if (strpos($page, $code) === FALSE) {
return false;
} else {
return true;
}
}
?>
You may want to swap that simple strpos out for a regular expression, but this will do the trick.
You need to do the 2 things:
1) get the content of remote url
2) check if the content contains your string:
if ( stristr($content, 'your_desired_string') )
{
echo ' Yes, found';
}
there are great libraries for crawling websites like cURL but in your case it seems to be an overkill to use it. If you want to use the cURL library I recommend the Snoopy-class to you which is very simple to use.
Felix

Changing Text in PHP

I haven't found anytihng in Google or the PHP manual, believe it or not. I would've thought there would be a string operation for something like this, maybe there is and I'm just uber blind today...
I have a php page, and when the button gets clicked, I would like to change a string of text on that page with something else.
So I was wondering if I could set the id="" attrib of the <p> to id="something" and then in my php code do something like this:
<?php
$something = "this will replace existing text in the something paragraph...";
?>
Can somebody please point me in the right direction? As the above did not work.
Thank you :)
UPDATE
I was able to get it working using the following sample:
Place this code above the <html> tag:
<?php
$existing = "default message here";
$something = "message displayed if form filled out.";
$ne = $_REQUEST["name"];
if ($ne == null) {
$output = $existing;
} else {
$output = $something;
}
?>
And place the following where ever your message is to be displayed:
<?php echo $output ?>
As far as I can get from your very fuzzy question, usually you don't need string manipulation if you have source data - you just substitute one data with another, this way:
<?php
$existing = "existing text";
$something = "this will replace existing text in the something paragraph...";
if (empty($_GET['button'])) {
$output = $existing;
} else {
$output = $something;
}
?>
<html>
<and stuff>
<p><?php echo $output ?></p>
</html>
but why not to ask a question bringing a real example of what you need? instead of foggy explanations in terms you aren't good with?
If you want to change the content of the paragraph without reloading the page you will need to use JavaScript. Give the paragraph an id.<p id='something'>Some text here</p> and then use innerHTML to replace it's contents. document.getElementById('something').innerHTML='Some new text'.
If you are reloading the page then you can use PHP. One way would be to put a marker in the HTML and then use str_replace() to insert the new text. eg <p><!-- marker --></p> in the HTML and $html_string = str_replace('<!-- marker -->', 'New Text', $html_string) assuming $html_string contains the HTML to output.
If you are looking for string manipulation and conversion you can simply use the str_replace function in php.
Please check this: str_replace()
If you're using a form (which I'm assuming you do) just check if the variable is set (check the $_POST array) and use a conditional statement. If the condition is false then display the default text, otherwise display something else.

Categories