如果您可以接受重命名包含空格的标记,那么 tidy 也是一个不错的选择,因为它也适用于 XML:
$xml = simplexml_load_string(
tidy_repair_string($string, ['input-xml' => 1])
);
echo "SimpleXML::asXML():\n", $xml->asXML(), "\n\n";
它重命名标签并创建属性:
SimpleXML::asXML():
<?xml version="1.0"?>
<Public Transport="" Rules="">
<PublicTransport id="0">
<Issued>null</Issued>
<Files><localfile> <location>Citybus</location>
<format>Events</format> </localfile></Files>
</PublicTransport>
</Public>
缩进等还有更多选项,这里有一个完整的例子:
<?php
/**
* How to parse XML files with errors using Simplexml in PHP?
*
* @link http://stackoverflow.com/q/15620492/367456
*/
$string = '<?xml version="1.0" ?>
<Public Transport Rules>
<PublicTransport id="0">
<Issued>null</Issued>
<Files><localfile>
<location>Citybus</location>
<format>Events</format>
</localfile>
</Files>
</PublicTransport>
</Public Transport Rules>';
echo "Broken:\n", $string, "\n\n";
$fixed = tidy_repair_string($string, ['input-xml' => 1, 'output-xml' => 1, 'indent' => 1]);
echo "Fixed:\n", $fixed, "\n\n";
$xml = simplexml_load_string(tidy_repair_string($string, ['input-xml' => 1]));
echo "SimpleXML::asXML():\n", $xml->asXML(), "\n\n";
并输出:
Broken:
<?xml version="1.0" ?>
<Public Transport Rules>
<PublicTransport id="0">
<Issued>null</Issued>
<Files><localfile>
<location>Citybus</location>
<format>Events</format>
</localfile>
</Files>
</PublicTransport>
</Public Transport Rules>
Fixed:
<?xml version="1.0"?>
<Public Transport="" Rules="">
<PublicTransport id="0">
<Issued>null</Issued>
<Files><localfile>
<location>Citybus</location>
<format>Events</format> </localfile></Files>
</PublicTransport>
</Public>
SimpleXML::asXML():
<?xml version="1.0"?>
<Public Transport="" Rules="">
<PublicTransport id="0">
<Issued>null</Issued>
<Files><localfile> <location>Citybus</location>
<format>Events</format> </localfile></Files>
</PublicTransport>
</Public>