dongzanghong4379 2014-09-09 13:47
浏览 39

使用PHP自定义的Xml解析器

My xml tag format is

<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>

I want to load This xml file and display result in format like

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

I have tried this PHP code

$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());
}

but $node give me empty result,How can I fix it or where I am wrong.

  • 写回答

1条回答 默认 最新

  • douzhi1879 2014-09-11 11:14
    关注

    I personally hate xml, I know it's a mature standard, but I hate working with non-native data stores. Even databases irk me.

    If I may refactor your code a bit...

    //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');
    }
    

    then you can output pretty simply

    $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>";
    }   
    

    This outputs

    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
    

    I leave it up to you to slice and dice your strings for prettiness.

    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度