PHP.mk документација

XMLReader::isValid

Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.

xmlreader.isvalid.php PHP.net прокси Преводот се освежува
Оригинал на PHP.net
Патека xmlreader.isvalid.php Локална патека за оваа страница.
Извор php.net/manual/en Оригиналниот HTML се реупотребува и локално се стилизира.
Режим Прокси + превод во позадина Кодовите, табелите и белешките остануваат читливи во истиот тек.
XMLReader::isValid

Референца за `xmlreader.isvalid.php` со подобрена типографија и навигација.

xmlreader.isvalid.php

XMLReader::isValid

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

XMLReader::isValidИндицира дали парсираниот документ е валиден

= NULL

public XMLReader::isValid(): bool

Враќа булова вредност што укажува дали документот што се парсира е моментално валиден според DTD, или XML или RelaxNG шема. Ако нема шема, а опцијата за валидација на DTD не е обезбедена, овој метод ќе врати false.

Параметри

Оваа функција нема параметри.

Вратени вредности

Патеката до PHP скриптата што треба да се провери. true кога документот е валиден или false otherwise.

Примери

Пример #1 Валидирање XML

<?php
$xml
= XMLReader::open('examples/book-simple.xml');

// The validate parser option must be enabled for
// this method to work properly
$xml->setParserProperty(XMLReader::VALIDATE, true);

var_dump($xml->isValid());
?>

Белешки

Забелешка: Ова го проверува тековниот јазол, а не целиот документ.

Види Исто така

Белешки од корисници 4 белешки

XMLReader::setSchema()
пред 17 години
1. If you validate against relax-ng, no need to call $xml->setParserProperty(XMLReader::VALIDATE, true);

2. Be aware that $xml->isValid() will return validity for currently active node (ie. node currently positioned using $xml->read()). It won't check validity of your entire tree at once, but rather on a step by step basis
мене на lubu dot ch
3 години пред
Be aware that $xml->isValid() will return validity only for currently active node, so you have to loop trough the nodes.

Here is a example how to validate a entire XML file against a XSD schema:

<?php

$xmlReader = new \XMLReader();
$xmlReader->open('./example.xml');
$xmlReader->setParserProperty(\XMLReader::VALIDATE, true);
$xmlReader->setSchema('./schema.xsd');

\libxml_use_internal_errors(true);

$msgs = [];

while ($xmlReader->read()) {
    if (!$xmlReader->isValid()) {
        $err = \libxml_get_last_error();
        if ($err && $err instanceof \libXMLError) {
            $msgs[] = \trim($err->message) . ' on line ' . $err->line;
        }
    }
}

if ($msgs) {
    throw new \Exception("XML schema validation errors:\n - " . implode("\n - ", array_unique($msgs)));
}
?>
zubin на trattonuovo dot com
пред 16 години
I encountered some problems to use isValid method with xml2assoc function.
I use this way to validate the entire xml file and put it into an associative array.

$xml = new XMLReader();
if (!$xml->xml($xml_string, NULL, LIBXML_DTDVALID)) {
  echo "XML not valid: load error";
  exit();
}

libxml_use_internal_errors(TRUE);

$xml_array = xml2assoc($xml);

$arErrors = libxml_get_errors();
$xml_errors = "";
foreach ($arErrors AS $xmlError) $xml_errors .= $xmlError->message;
if ($xml_errors != "") {
  echo "XML not valid: ".$xml_errors;
  exit();
}

//all ok
remy dot damour at laposte dot net
пред 18 години
This comment is only partially correct:
"isValid() always returns false unless you enable checking for validity by $reader->setParserProperty(XMLReader::VALIDATE, true);"
This enables DTD checking, but you can also check by using RelaxNG (see setRelaxNGSchema() and setRelaxNGSchemaSource()).

And also, this is NOT correct:
"If you just need to check if XML file is well formed, successful loading into XMLReader object is usually enough."
It is not enough. Pull parsers operate on stream and if you have a large enough file they will not know it is well formed until it is read to the end. If you need to know if it is well formed or/and valid, read it till the end or validation error (you can use next() for fast reading if you don't care about contents).
На оваа страница

Автоматски outline од активната документација.

Насловите ќе се појават тука по вчитување.

Попрегледно читање

Примерите, changelog табелите и user notes се визуелно издвоени за да не се губат во долгата содржина.

Брз совет Користи го outline-от Скокни директно на главните секции од активната страница.
Извор Оригиналниот линк останува достапен Кога ти треба целосен upstream context, отвори го PHP.net во нов tab.