affiliatex
affiliatex

Reputation: 67

How do I fetch a new url if 404 returned Simple DOM PHP

I'm trying to get HTML from a url using simple dom. There are only 2 possible variations of the URL's i'm trying to get. What I want to do is if I check the headers and when I get a 404, I need to fetch the other URL.

Here's my code below. I'm getting a "unexpected ELSE" error. I'm not sure where to go from here. Please don't laugh too hard at my code, I'm still fairly new to php :)

Any help would be much appreciated.

<?php                        
require_once 'libs/simple_html_dom.php';
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
list($chuck, $keep) = explode('=', $url);
list($chuck1, $keep1) = explode('/', $keep);
$myURL = "http://www.example.com/" . $chuck1 . "/" . $keep1 . "-url-1.html";
$myURL2 = "http://www.exmple.com/" . $chuck1 . "/" . $keep1 . "-url-2.html";
$patterns = array();
$patterns[0] = 'find';
$patterns[1] = 'find2';
$patterns[2] = 'find3';
$replacements = array();
$replacements[0] = 'replace1';
$replacements[1] = 'replace2';
$replacements[2] = 'replace3';
$data = str_replace($patterns, $replacements, $myURL, $element);
$data2 = str_replace($patterns, $replacements, $myURL2, $element);
$headers = @get_headers($data);
if (is_array($headers)){
if(strpos($headers[0], '404 Not Found'))
    $html2 = @file_get_html($data2);
    $element = $html->find('div[class="cool-attribute"]', 0);
    echo str_replace($patterns, $replacements, $element);
else
    $html = @file_get_html($data);
    $element = $html->find('div[class="cool-attribute"]', 0);
    echo str_replace($patterns, $replacements, $element);

}

?>

Upvotes: 0

Views: 1044

Answers (1)

AJPerez
AJPerez

Reputation: 3595

You're missing the braces { ... } in your if-else block.

Fix it this way:

if (strpos($headers[0], '404 Not Found')) {
    $html2 = @file_get_html($data2);
    $element = $html->find('div[class="cool-attribute"]', 0);
    echo str_replace($patterns, $replacements, $element);
} else {
    $html = @file_get_html($data);
    $element = $html->find('div[class="cool-attribute"]', 0);
    echo str_replace($patterns, $replacements, $element);
}

Just adding tabs for indenting the code doesn't make it a block. You have to enclose it in { } for that. When you place a if (or an else, while, etc.) without braces, it only applies to the next line of code. In this case, the code you wrote is equivalent to this:

if (strpos($headers[0], '404 Not Found')) {
    $html2 = @file_get_html($data2);
}
$element = $html->find('div[class="cool-attribute"]', 0);
echo str_replace($patterns, $replacements, $element);
else // else? why is there an else here, it's not after an if! :)
$html = @file_get_html($data);
$element = $html->find('div[class="cool-attribute"]', 0);
echo str_replace($patterns, $replacements, $element);

Upvotes: 1

Related Questions