下一頁功能將這樣的伎倆:
/**
* @param $xml string Your XML
* @param $old string Name of the old tag
* @param $new string Name of the new tag
* @return string New XML
*/
function renameTags($xml, $old, $new)
{
$dom = new DOMDocument();
$dom->loadXML($xml);
$nodes = $dom->getElementsByTagName($old);
$toRemove = array();
foreach ($nodes as $node)
{
$newNode = $dom->createElement($new);
foreach ($node->attributes as $attribute)
{
$newNode->setAttribute($attribute->name, $attribute->value);
}
foreach ($node->childNodes as $child)
{
$newNode->appendChild($node->removeChild($child));
}
$node->parentNode->appendChild($newNode);
$toRemove[] = $node;
}
foreach ($toRemove as $node)
{
$node->parentNode->removeChild($node);
}
return $dom->saveXML();
}
// Load XML from file data.xml
$xml = file_get_contents('data.xml');
$xml = renameTags($xml, 'modelNumber', 'number');
$xml = renameTags($xml, 'salePrice', 'price');
echo '<pre>'; print_r(htmlspecialchars($xml)); echo '</pre>';
是您的XML故意畸形? – kapa
這些文件由多個來源提供 - 標籤名稱不受我控制。 –
因此像' Data modelNumber>'(不同的結尾/結束標記)這樣的錯誤是否正常?因爲那樣你就不能真正用XML解析器解析這個文檔(比如PHP DOM)。 –
kapa