태그 보관물: domdocument

domdocument

DomDocument (PHP)에 의해 잘 구성되지 않은 HTML을로드 할 때 경고 비활성화 이러한 디버깅 / 경고 동작을

일부 HTML 파일을 구문 분석해야하지만 형식이 올바르지 않고 PHP가 경고를 출력합니다. 프로그래밍 방식으로 이러한 디버깅 / 경고 동작을 피하고 싶습니다. 조언하십시오. 감사합니다!

암호:

// create a DOM document and load the HTML data
$xmlDoc = new DomDocument;
// this dumps out the warnings
$xmlDoc->loadHTML($fetchResult);

이:

@$xmlDoc->loadHTML($fetchResult)

경고를 억제 할 수 있지만 프로그래밍 방식으로 경고를 캡처하려면 어떻게해야합니까?



답변

다음을 사용하여 임시 오류 처리기를 설치할 수 있습니다. set_error_handler

class ErrorTrap {
  protected $callback;
  protected $errors = array();
  function __construct($callback) {
    $this->callback = $callback;
  }
  function call() {
    $result = null;
    set_error_handler(array($this, 'onError'));
    try {
      $result = call_user_func_array($this->callback, func_get_args());
    } catch (Exception $ex) {
      restore_error_handler();
      throw $ex;
    }
    restore_error_handler();
    return $result;
  }
  function onError($errno, $errstr, $errfile, $errline) {
    $this->errors[] = array($errno, $errstr, $errfile, $errline);
  }
  function ok() {
    return count($this->errors) === 0;
  }
  function errors() {
    return $this->errors;
  }
}

용법:

// create a DOM document and load the HTML data
$xmlDoc = new DomDocument();
$caller = new ErrorTrap(array($xmlDoc, 'loadHTML'));
// this doesn't dump out any warnings
$caller->call($fetchResult);
if (!$caller->ok()) {
  var_dump($caller->errors());
}


답변

요구

libxml_use_internal_errors(true);

로 처리하기 전에 $xmlDoc->loadHTML()

이것은 libxml2 에게 PHP로 오류와 경고 를 보내지 않도록 지시 합니다. 그런 다음 오류를 확인하고 직접 처리 하려면 준비가되면 libxml_get_last_error () 및 / 또는 libxml_get_errors ()를 참조 할 수 있습니다.


답변

경고를 숨기려면 libxml내부적으로 구문 분석을 수행하는 데 사용되는 특수 지침을 제공 해야합니다.

libxml_use_internal_errors(true);
$dom->loadHTML($html);
libxml_clear_errors();

libxml_use_internal_errors(true)당신이 오류와 경고를 직접 처리 할거야 당신은 스크립트의 출력까지 혼란에 원하지 않는 것을 나타냅니다.

이것은 @운영자 와 동일하지 않습니다 . 경고는 배후에서 수집되며 libxml_get_errors()로깅을 수행하거나 문제 목록을 호출자에게 반환하려는 경우 사용하여 검색 할 수 있습니다 .

수집 된 경고를 사용하는지 여부에 관계없이 항상을 호출하여 대기열을 지워야합니다 libxml_clear_errors().

국가 보존

사용 libxml하는 다른 코드가있는 경우 코드가 오류 처리 의 전역 상태를 변경하지 않는지 확인하는 것이 좋습니다 . 이를 위해 반환 값 libxml_use_internal_errors()을 사용하여 이전 상태를 저장할 수 있습니다 .

// modify state
$libxml_previous_state = libxml_use_internal_errors(true);
// parse
$dom->loadHTML($html);
// handle errors
libxml_clear_errors();
// restore
libxml_use_internal_errors($libxml_previous_state);


답변

“LIBXML_NOWARNING”및 “LIBXML_NOERROR”옵션 설정도 완벽하게 작동합니다.

$dom->loadHTML($html, LIBXML_NOWARNING | LIBXML_NOERROR);


답변