PHP에서 경고를 표시하지 않고 문자열이 유효한 XML인지 확인하는 방법
이 함수를 사용하여 xml로 된 문자열의 유효성을 확인하려고 했지만 많은 경고 메시지가 표시됩니다.
오류를 @
억제하고(처음에) 예상되는 경고 기능을 표시하지 않고 문자열이 유효한 XML인지 확인하려면 어떻게 해야 합니까?
libxml_use_internal_errors()를 사용하여 모든 XML 오류를 억제하고 libxml_get_errors()를 사용하여 이후에 오류를 반복합니다.
libxml_use_internal_errors(true);
$doc = simplexml_load_string($xmlstr);
$xml = explode("\n", $xmlstr);
if (!$doc) {
$errors = libxml_get_errors();
foreach ($errors as $error) {
echo display_xml_error($error, $xml);
}
libxml_clear_errors();
}
설명서에서 다음을 참조하십시오.
문서를 로드할 때 XML 오류를 처리하는 것은 매우 간단한 작업입니다.사용
libxml
기능은 문서를 로드할 때 모든 XML 오류를 억제한 다음 오류를 반복할 수 있습니다.그
libXMLError
객체, 반환된 사용자libxml_get_errors()
를 포함한 여러 속성을 포함합니다.message
,line
그리고.column
오류의 (위치).
libxml_use_internal_errors(true);
$sxe = simplexml_load_string("<?xml version='1.0'><broken><xml></broken>");
if (!$sxe) {
echo "Failed loading XML\n";
foreach(libxml_get_errors() as $error) {
echo "\t", $error->message;
}
}
참조:
이거 드셔보세요.
//check if xml is valid document
public function _isValidXML($xml) {
$doc = @simplexml_load_string($xml);
if ($doc) {
return true; //this is valid
} else {
return false; //this is not valid
}
}
내 버전은 다음과 같습니다.
//validate only XML. HTML will be ignored.
function isValidXml($content)
{
$content = trim($content);
if (empty($content)) {
return false;
}
//html go to hell!
if (stripos($content, '<!DOCTYPE html>') !== false) {
return false;
}
libxml_use_internal_errors(true);
simplexml_load_string($content);
$errors = libxml_get_errors();
libxml_clear_errors();
return empty($errors);
}
테스트:
//false
var_dump(isValidXml('<!DOCTYPE html><html><body></body></html>'));
//true
var_dump(isValidXml('<?xml version="1.0" standalone="yes"?><root></root>'));
//false
var_dump(isValidXml(null));
//false
var_dump(isValidXml(1));
//false
var_dump(isValidXml(false));
//false
var_dump(isValidXml('asdasds'));
여기 제가 얼마 전에 쓴 수업의 작은 부분이 있습니다.
/**
* Class XmlParser
* @author Francesco Casula <fra.casula@gmail.com>
*/
class XmlParser
{
/**
* @param string $xmlFilename Path to the XML file
* @param string $version 1.0
* @param string $encoding utf-8
* @return bool
*/
public function isXMLFileValid($xmlFilename, $version = '1.0', $encoding = 'utf-8')
{
$xmlContent = file_get_contents($xmlFilename);
return $this->isXMLContentValid($xmlContent, $version, $encoding);
}
/**
* @param string $xmlContent A well-formed XML string
* @param string $version 1.0
* @param string $encoding utf-8
* @return bool
*/
public function isXMLContentValid($xmlContent, $version = '1.0', $encoding = 'utf-8')
{
if (trim($xmlContent) == '') {
return false;
}
libxml_use_internal_errors(true);
$doc = new DOMDocument($version, $encoding);
$doc->loadXML($xmlContent);
$errors = libxml_get_errors();
libxml_clear_errors();
return empty($errors);
}
}
테스트용으로도 스트림 및 vfsStream과 잘 작동합니다.
사례.
때때로 Google Merchant XML 피드의 가용성을 확인합니다.
DTD가 없는 피드라 작동이 안 됩니다.
해결책
// disable forwarding those load() errors to PHP
libxml_use_internal_errors(true);
// initiate the DOMDocument and attempt to load the XML file
$dom = new \DOMDocument;
$dom->load($path_to_xml_file);
// check if the file contents are what we're expecting them to be
// `item` here is for Google Merchant, replace with what you expect
$success = $dom->getElementsByTagName('item')->length > 0;
// alternatively, just check if the file was loaded successfully
$success = null !== $dom->actualEncoding;
length
위에는 파일에 실제로 나열된 제품의 수가 포함되어 있습니다.대신 태그 이름을 사용할 수 있습니다.
논리
다른 태그 이름을 호출할 수 있습니다(item
Google Merchant용으로 사용했습니다. 사례는 다를 수 있습니다) 또는 다른 속성을 읽어보십시오.$dom
이의 제기 자체.논리는 동일하게 유지됩니다. 파일을 로드할 때 오류가 있었는지 확인하는 것보다 실제로 파일을 조작(또는 실제로 필요한 값이 포함되어 있는지 구체적으로 확인)하는 것이 더 신뢰할 수 있다고 생각합니다.
가장 중요한 것은 이와 달리 XML에 DTD가 필요하지 않습니다.
해결책
<?php
/**
* 檢查XML是否正確
*
* @param string $xmlstr
* @return bool
*/
public function checkXML($xmlstr)
{
libxml_use_internal_errors(true);
$doc = simplexml_load_string($xmlstr);
if (!$doc) {
$errors = libxml_get_errors();
if (count($errors)) {
libxml_clear_errors();
return false;
}
}
return true;
}
언급URL : https://stackoverflow.com/questions/4554233/how-check-if-a-string-is-a-valid-xml-with-out-displaying-a-warning-in-php
'programing' 카테고리의 다른 글
R에서 데이터베이스 연결의 필터에서 문자 벡터를 사용하는 방법은 무엇입니까? (0) | 2023.09.02 |
---|---|
div 내부에 이미지(img)를 맞추고 가로 세로 비율을 유지하려면 어떻게 해야 합니까? (0) | 2023.09.02 |
평가는 사악합니다...그럼 무엇을 대신 사용해야 할까요? (0) | 2023.09.02 |
C 또는 C++에서 포인터 매개 변수를 NULL/nullptr에 대해 확인해야 합니까? (0) | 2023.09.02 |
스프링 MVC: 와 태그의 차이점은 무엇입니까? (0) | 2023.09.02 |