スペースを含むタグの名前を変更しても問題が解決しない場合は、XMLでも機能するため、tidyを使用することをお勧めします。
$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>