NYCPHP Meetup

NYPHP.org

[nycphp-talk] Transforming XML with XSL (XsltProcessor problems)

Daniel Convissor danielc at analysisandsolutions.com
Thu Mar 12 23:20:10 EDT 2009


Hey Folks:

On Thu, Mar 12, 2009 at 09:44:08PM -0400, Ajai Khattri wrote:
> 
> I have to say, the error reporting for the XML and XSLT functions are 
> terrible.

Here's how I load XML.  Requres track_errors to be on.  Sorry about the 
line wrapping.


$xml_string = '';
$schema_file = '';

if (($dom = @DOMDocument::loadXML($xml_string)) == false) {
    $error = 'Malformed XML: ' . $php_errormsg;
} elseif ((@$dom->schemaValidate($schema_file)) == false) {
    $error = 'XML violates schema ' . $schema_file . ': '
            . format_schemavalidate_error($php_errormsg);
} else {
    if (($sxml = @simplexml_import_dom($dom)) === false) {
        $error = 'Malformed XML (SimpleXML): ' . $php_errormsg;
    }
}

if (!empty($error)) {
    // process...
}



/**
 * Boils down XML schema validation error messages into something
 * humans can easily comprehend
 *
 * @param string $error  the $php_errormsg produced by DOM
 *                       schemaValidate()
 *
 * @return string
 */
function format_schemavalidate_error($error) {
    $error = preg_replace('/\s+/', ' ', $error);

    if (preg_match("/The element: '([^']+)'/", $error, $match)) {
        $error = $match[1] . ' has invalid value . ';
    } elseif (preg_match("/Element '([^']+)', attribute '([^']+)'/", 
$error, $match)) {
        $error = $match[2] . ' attribute of ' . $match[1] . ' has invalid 
value . ';
    } elseif (preg_match("/Element '([^']+)': The attribute '([^']+)' is 
required/", $error, $match)) {
        $error = $match[2] . ' attribute of ' . $match[1] . ' is missing 
. ';
    } elseif (preg_match("/is not a valid value of the atomic type 
'({.*})?([^']+)'/", $error, $match)) {
        $error = $match[2] . ' has invalid value . ';
    } elseif (preg_match('/Expecting: ([^.]+)/', $error, $match)) {
        $error = $match[1] . ' is missing . ';
    } elseif (preg_match('/(Expected is|Expected is one of) \( 
({.*})?([^.]+) \)/', $error, $match)) {
        $error = $match[3] . ' is missing . ';
    }

    return $error;
}


Enjoy,

--Dan

-- 
 T H E   A N A L Y S I S   A N D   S O L U T I O N S   C O M P A N Y
            data intensive web and database programming
                http://www.AnalysisAndSolutions.com/
 4015 7th Ave #4, Brooklyn NY 11232  v: 718-854-0335 f: 718-854-0409



More information about the talk mailing list