Last active
June 1, 2016 20:40
-
-
Save volkan/0d3af41be13a628201b1cee82246d095 to your computer and use it in GitHub Desktop.
fix xml
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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