I
I
Ivan Antonov2016-09-28 13:50:40
PHP
Ivan Antonov, 2016-09-28 13:50:40

How to validate an XML file using XMLReader?

Here is a piece of code:

$URI = /* Ссылка на XML или архив */;
$document = new \XMLReader;

if (/* Если передан архив */) {
   $xml = /* Абра-кадабра */;
} else {
   $xml = $URI;
}

if ( ! $document->open($xml)) {
    throw new XmlException('Ошибка про попытке прочитать файл ' . $URI);
}

Everything seems to be clear. BUT, if you specify the $URI of a regular html page, the expression $document->open($xml)still returns true.
How to check if a document is XML?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ivan Antonov, 2016-09-28
@antonowano

I tried to use the XSD schema, but I also got true on all attempts.
Therefore, I solved the issue by downloading the archive to the server and simultaneously checking it for correctness.

private function upload($uri, $temp)
{
    if (preg_match('/[^\/]+(.(gz)|(bz2))$/i', $uri, $match)) {
        $compress = array(
            '.gz' => 'compress.zlib://',
            '.bz2' => 'compress.bzip2://'
        );
        $source = $compress[ $match[1] ] . $uri;
    } else {
        $source = $uri;
    }

    $hR = fopen($source, "r");
    $hW = fopen($temp, "w");
    $part = 0;

    while ( ! feof($hR)) {
        $str = fread($hR, 1024);

        if ($part == 0 && stripos($str, '<?xml') === false) {
            throw new \Exception('Передаваемый файл не XML.');
        }

        fwrite($hW, $str, strlen($str));
        $part++;
    }

    fclose($hW);
    fclose($hR);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question