file_get_contents()

How do I create a variable that contains the html of a site using file_get_contents()?

Based on http://php.net/manual/en/function.file-get-contents.php, I’ve tried many variations of this short script with no joy.

<?php
$homepage = file_get_contents('http://www.example.com');
$txt = fopen($homepage,'r');
?>

How do I avoid the warning and create a variable that I can fopen using file_get_contents()?

$txt = file_get_contents('http://www.example.com');
That is all. You do not use fopen or other f* functions with this.

Thanks logic_earth.

So, when I run this script:

<?php
$file = file_get_contents('http://comlinc.com/file_get_contents3.php');
$var =  substr($file,strripos($file,"ViewPropertyOrOwners"));
var_dump($var);
?>

It targets the string in the javascript. I want to target the “ViewPropertyOrOwners” string in the html.

Why doesn’t my script target the string in the html first?

Here’s the link for the script: http://comlinc.com/test_121209.php

PHP has no concept of HTML or Javascript. If that is what you need, use the DOM functions. http://us2.php.net/DOM

I’m following you. Thanks.

I found this tutorial at http://www.php4every1.com/tutorials/php-domdocument-tutorial/

It produces this little script:

<?php
$dom = new DOMDocument();
$dom->load('http://www.w3schools.com/XML/simple.xml');
$food = $dom->getElementsByTagName('food');
var_dump($food);
?>

It produces this result: object(DOMNodeList)#2 (0) { }

How do I see what’s in it? var_dump will display the contents of a “normal” array. How do I display the contents of a “object” array. I’m new to objects and don’t know which keywords to google.

Got it!

<?php
$DOM = new DOMDocument();
$DOM->loadHTMLFile('http://www.w3.org');

$items = $DOM->getElementsByTagName('a');

for ($i = 0; $i < $items->length; $i++) {
    echo $items->item($i)->nodeValue . '<br/>';
}

?>

Thanks again for your help logic_earth, but then I’m sure you hear that all the time.

Note Bene: fopen wrappers must be enabled for this to work. Some server admins may disable this for security reasons, in which event cURL should be used. So if anyone tries this and it doesn’t work, that’s likely why.

Also, even if URL fopen is enabled, file_get_contents() can fail if the remote server checks the user agent of the request. Sometimes the default one is blocked. Twitter RSS feeds, for example, don’t like the default User Agent of my web server. You can set the user agent in file_get_contents() but it’s just as easy to use cURL in these cases.