Speed up development with full-stack environments for every branch.

Learn More

How to build a simple libxml error handler. [PHP]

Forked from Hello World.

56 Runs 768 Views 259 Copies
Saved

Saved

gtsolutions 373

gtsolutions
published 4 years ago

<?php

/**
 * PHP libxml
 * simple libxml error handler.
 * 
 */
libxml_use_internal_errors(true);

$xmlstr = "<?xml version='1.0' standalone='yes'?>
<animals>
 <animal>
  <names>DOG: This dog is bad</name>
  <names>Cat: This cat is ugly</name>
  <names>Wolf: This wolf is mean</name>
 </animal>
</animals>";

$doc = simplexml_load_string($xmlstr);
$xml = explode("\n", $xmlstr);

if (!$doc) {
    $errors = libxml_get_errors();

    foreach ($errors as $error) {
        echo display_xml_error($error, $xml);
    }

    libxml_clear_errors();
}

function display_xml_error($error, $xml) {
    //setting div style for nicer display
    $divStyle = ' background-color:#E8E8E3;
            padding:10px;
            color:#000;
            font-size:16px;
            width:600px;
            margin:0 auto;';
    $return = $xml[$error->line - 1] . "<br />";
    $return .= str_repeat('-', $error->column) . "<br />";

    switch ($error->level) {
        case LIBXML_ERR_WARNING:
            $return .= "This is a  libxml Warning $error->code: ";
            break;
        case LIBXML_ERR_ERROR:
            $return .= "This is a libxml Error $error->code: ";
            break;
        case LIBXML_ERR_FATAL:
            $return .= "This is a libxml Error $error->code: ";
            break;
    }

    $return .= "<br />" . trim($error->message) .
            "<br />  Line: $error->line" .
            "<br />  Column: $error->column";

    if ($error->file) {
        $return .= "<br />  File: $error->file";
    }

    return '<div style="' . $divStyle . '">' . $return . '</div>';
}

?>
Please login/signup to get access to the terminal.

Your session has timed out.

Dismiss (the page may not function properly).