2

I try to get the text from a website with the file_get_contents()-function in PHP.

        $myVariable = file_get_contents('myUrl/json/file.json?jsonp=loadSomething);

Unfortunately I keep getting the message

"Warning:
file_get_contents(myUrl/json/file.json?jsonp=loadSomething): 
failed to open stream: HTTP request failed! 
HTTP/1.1 404 Not Found in *path of my .php- file* on line 10"

In php.ini, allow_url_fopen is set to "On". I also already tried urlencode(). What can I do to get my code working?

4
  • and you, i.e the www-user have read-access to that directory? Commented Oct 18, 2015 at 14:45
  • How do you mean? The code is in the "helper.php"-file of a module, installed on my Joomla-page, so I believe, the www-user has read-access. Commented Oct 18, 2015 at 14:49
  • I mean, do you have proper user rights on json/? However, try use an absolute path if you not have done that yet. Commented Oct 18, 2015 at 14:53
  • The file I try to open is on another website. I can open the URL in my browser without problems, it displays a plain text message to me. And this is the message, I want to save in my variable. So as a www-user I do have access to the "file.json". Commented Oct 18, 2015 at 14:57

1 Answer 1

2

OK, the remote file is accessible. When file_get_contents fails, cURL is your friend :

function file_get_contents_curl($url) {
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)');
    $data = curl_exec($curl);
    curl_close($curl);
    return $data;
}

now try

$myVariable = file_get_contents_curl('myUrl/json/file.json?jsonp=loadSomething');
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your reply. I do not get any warnings or errors right now, but still, I don't receive the text of the website properly. Calling the function only appears to return "0".
@msu-welle - I begin to believe your remote site actively try to prevent scraping and such ... See update, trying to fake your call is made by a browser by CURLOPT_USERAGENT.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.