Skip to content

Instantly share code, notes, and snippets.

@volkan
Last active June 1, 2016 20:40
Show Gist options
  • Save volkan/0d3af41be13a628201b1cee82246d095 to your computer and use it in GitHub Desktop.
Save volkan/0d3af41be13a628201b1cee82246d095 to your computer and use it in GitHub Desktop.
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