更新时间:2023-02-06 15:56:38
虽然我认为 XMLWriter 最适合对于该任务(就像我的其他答案),如果你真的想用 SimpleXML 来做,方法如下:
Although I think XMLWriter is best suited for that task (like in my other answer), if you really want to do it with SimpleXML, here's how:
$fp = fopen('data.txt', 'r');
$xml = new SimpleXMLElement('<allproperty></allproperty>');
while ($line = fgetcsv($fp)) {
if (count($line) < 4) continue; // skip lines that aren't full
$node = $xml->addChild('aproperty');
$node->addChild('postcode', $line[0]);
$node->addChild('price', $line[1]);
$node->addChild('imagefilename', $line[2]);
$node->addChild('visits', $line[3]);
}
echo $xml->saveXML();
您会注意到输出不是那么干净:这是因为 SimpleXML 不允许您自动缩进标签.
You will notice that the output is not as clean: it's because SimpleXML doesn't allow you to automatically indent tags.