1
<?xml version="1.0" encoding="ISO-8859-1"?>

<Note>
<from>
Ahmad
</from>
<to>
Yasir
</to>
<body>
hello yasir.

</Note>

Above is my xml file which misses the ending tag of <body>. i want a php program that will detect this error and also fix the error and place the ending tag.

hakre
  • 193,403
  • 52
  • 435
  • 836

1 Answers1

0

If your looking for quick solution to fix unmatched tag, the following can do a trick:

libxml_use_internal_errors(true);
$file   = 'your_xml.xml';
$xml    = @simplexml_load_file($file);
$errors = libxml_get_errors();
foreach ($errors as $error)
{
  if (strpos($error->message, 'Opening and ending tag mismatch')!==false)
  {
    $tag   = trim(preg_replace('/Opening and ending tag mismatch: (.*) line.*/', '$1', $error->message));
    $lines = file($file, FILE_IGNORE_NEW_LINES);
    $line  = $error->line-1;
    $lines[$line] = '</'.$tag.'>'.$lines[$line];
    file_put_contents($file, implode("\n", $lines));
  }
}

You can consider using more proper approach like using PHP Tidy extension

related question : Fix malformed XML in PHP before processing using DOMDocument functions

Community
  • 1
  • 1
ajreal
  • 46,720
  • 11
  • 89
  • 119