繁体   English   中英

使用PHP自定义的Xml解析器

[英]Xml parser with customization using PHP

我的xml标记格式是

<transcript>
<messages>
    <message>
        <to>user1@localhost.local</to>
        <from>user2@localhost.local</from>
        <body>hello</body>
        <date>2014-09-09 14:14:17.652 IST</date>
    </message>
    <message>
        <to>user2@localhost.local</to>
        <from>user1@localhost.local</from>
        <body>hi dear</body>
        <date>2014-09-10 14:14:17.652 IST</date>
    </message>
</messages>
</transcript>

我想加载此xml文件并以类似以下格式显示结果

2014-09-09 - Tuesday
(2:14 PM ) user1 : hello
2014-09-10 - Wednesday
(2:14 PM )user2 : hi dear

我已经试过这个PHP代码

$xml_file_path='filename_with_path';
$XMLReader->open($xml_file_path);
while ($XMLReader->read() && $XMLReader->name !== "transcript");
while ($XMLReader->read() && $XMLReader->name !== "messages");
while ($XMLReader->read() && $XMLReader->name !== "message");
while ($XMLReader->name === "message") {
    $node = new SimpleXMLElement($XMLReader->readOuterXML());
}

但是$ node给我空结果,我该如何解决它或出现错误的地方。

我个人讨厌xml,我知道它是一个成熟的标准,但是我讨厌使用非本地数据存储。 甚至数据库也让我讨厌。

如果我可以重构一下您的代码...

//This turns your xml into a php object, which can be manipulated more directly
if (file_exists('text.xml')) {
    $xml = simplexml_load_file('text.xml');
}

那么你可以很简单地输出

$totalMessages = count( $xml->messages->message );
for($i = 0; $i < $totalMessages; $i++){
    echo "{$xml->messages->message[$i]->date}<br>
    {$xml->messages->message[$i]->from}: {$xml->messages->message[$i]->body}<br><br>";
}   

这个输出

2014-09-09 14:14:17.652 IST
user2@localhost.local: hello

2014-09-10 14:14:17.652 IST
user1@localhost.local: hi dear

我将它交给您,以将您的琴弦切成薄片并切成小块,以备不时之需。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM