fix xml
<?php | |
$xml = ' | |
<products> | |
<product> | |
<id>1</id> | |
</product> | |
<product> | |
<id>2</id> | |
</product> | |
<product> | |
<id>3</id> | |
</product> | |
<product> | |
<id>4</id> | |
</product> | |
<product> | |
<id>5</id> | |
<a>bozuk<a> | |
</product> | |
</products> | |
'; | |
echo fixXML($xml, 'product'); | |
function fixXML($xml, $nodeName) { | |
$patternTag = sprintf('/<%s[\s>].*?<\/%s>/s', $nodeName, $nodeName); | |
preg_match_all($patternTag, $xml, $matches); | |
$start = '<?xml version="1.0" encoding="utf-8"?><root>'; | |
$end = '</root>'; | |
$list = []; | |
$wrongItem = []; | |
$doc = new \DOMDocument(); | |
foreach ($matches[0] as $key => $item) { | |
try { | |
$tmpXML = $start . $item . $end; | |
$status = @$doc->loadXML($tmpXML); | |
if ($status == false) { | |
throw new \Exception; | |
} | |
$list[] = $item; | |
} catch (\Exception $e) { | |
$wrongItem[] = $item; | |
} | |
} | |
$xml = $start . implode("\n", $list) . $end; | |
return $xml; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment