简体   繁体   中英

Validating and possibly correcting an XML file that I have

I have an XML file (random resource ) that I need to use. I am using PHP DOM Document to process this document and DOMXPath to query the object. However, the XPath queries are not returning any kind of data (resultset->length = 0). The query is correct, and I am not worried about the syntax to it. I also experimented with DOMDOcument->getElementsByTagName("tag") and this returns a null result as well.

In the context above, how can I check if my DOMDocument was able to load when I did call the

DOMDocument->Load('file.xml')


[also tried 

$xmlFile = file_get_contents('file.xml')
DOMDocument->loadXML($xmlFile)]

I am assuming if the XML file is fault then in all likelihood I cannot query the DOMDocument at all ? Is there anyway for me to check if the a) the document was loaded at all when I called DOMDocument->Load/loadXML methods b) validate the XML file using external resources (w3 schools validator is the only one I know) c) if the XML file is incorrect, anyway that I can rectify it ?

Thanks to all those who take the time out and read this.

Best, Parijat Kalia

Try flipping this on before doing anything:

libxml_use_internal_errors(true);

Then after loading your XML, look for errors using:

$errors = libxml_get_errors();

You can iterate over $errors (it's an array of libXMLError objects).

For example:

libxml_use_internal_errors(true);

try
{
    $doc = new DOMDocument();
    $doc->load("somebadxmlfile.xml");
}
catch (Exception $e)
{
    $errors = libxml_get_errors();

    foreach ($errors as $error)
    {
        echo $error->message . " [ Line: " . $error->line . " | Column: " . $error->column . " | Level: " . $error->level . " | File: " . $error->file . " ]";
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM