0

간단한 DOM을 사용하여 URL에서 HTML을 가져 오려고합니다. URL 중 2 가지 가능한 유사 콘텐츠 만 있습니다. 내가하고 싶은 일은 헤더를 확인하면 404가 나오면 다른 URL을 가져와야한다는 것입니다.404가 반환 된 경우 새 URL을 가져 오는 방법 간단한 DOM PHP

다음은 아래 코드입니다. "예기치 않은 오류"오류가 발생합니다. 나는 여기서 어디로 가야할지 모르겠다. 제발 너무 열심히 내 코드에서 웃지 마세요, 난 여전히 PHP에 상당히 새로운거야 :)

어떤 도움을 많이 주시면 감사하겠습니다.

<?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); 

}

?>

답변

1

귀하의 경우 - 다른 블록에 당신은 괄호 { ... }을 놓치고있어.

수정 그것은이 방법 :이 블록하지 않는 코드를 들여

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); 
} 

그냥 추가 탭. 그것에 대해서는 { }에 동봉해야합니다. 중괄호없이 if (또는 else, while 등)을 배치하면 다음 코드 행에만 적용됩니다. 이 경우 작성한 코드는 다음과 같습니다.

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); 
관련 문제