php check if valid xml

Solutions on MaxInterview for php check if valid xml by the best coders in the world

showing results for - "php check if valid xml"
Esteban
03 Sep 2019
1/**
2 * Class XmlParser
3 * @author Francesco Casula <fra.casula@gmail.com>
4 */
5class XmlParser
6{
7    /**
8     * @param string $xmlFilename Path to the XML file
9     * @param string $version 1.0
10     * @param string $encoding utf-8
11     * @return bool
12     */
13    public function isXMLFileValid($xmlFilename, $version = '1.0', $encoding = 'utf-8')
14    {
15        $xmlContent = file_get_contents($xmlFilename);
16        return $this->isXMLContentValid($xmlContent, $version, $encoding);
17    }
18
19    /**
20     * @param string $xmlContent A well-formed XML string
21     * @param string $version 1.0
22     * @param string $encoding utf-8
23     * @return bool
24     */
25    public function isXMLContentValid($xmlContent, $version = '1.0', $encoding = 'utf-8')
26    {
27        if (trim($xmlContent) == '') {
28            return false;
29        }
30
31        libxml_use_internal_errors(true);
32
33        $doc = new DOMDocument($version, $encoding);
34        $doc->loadXML($xmlContent);
35
36        $errors = libxml_get_errors();
37        libxml_clear_errors();
38
39        return empty($errors);
40    }
41}