【问题标题】:SimpleXML removes tags in nodeSimpleXML 删除节点中的标签
【发布时间】:2015-12-21 20:53:29
【问题描述】:

我想解析一个名为 Folker 的应用程序生成的 XML 文件。这是一个转录口语文本的应用程序。有时它将行保存为可以用 SimpleXML 解析的良好格式,但有时却不能。

这条线不错:

<contribution speaker-reference="KU" start-reference="TLI_107" end-reference="TLI_109" parse-level="1">
    <unparsed>ich überLEG mir das [nochma:l,]</unparsed>
</contribution>

这行不是:

<contribution speaker-reference="VK" start-reference="TLI_108" end-reference="TLI_111" parse-level="1">
    <unparsed>[JA:_a; ]<time timepoint-reference="TLI_109"/>ja,<time timepoint-reference="TLI_110"/>also (.) wie [geSAGT;]</unparsed>
</contribution>

在第二行中,SimpleXML 删除了 unparsed 节点内的标签。

我怎样才能让 SimpleXML 不删除这些标签,而是将其解析为更深的节点或作为对象输出,例如像这样(只是在 JSON 中以便更好地理解):

"contribution": {
    "speaker-reference": "VK",
    "start-reference": "TLI_108",
    "end-reference": "TLI_111",
    "parse-level": "1",
    "unparsed": {
        "content": "[JA:_a; ]",
        "time": {
            [
                "timepoint-reference": "TLI_109",
                "content": "ja,"
            ],
            [
                "timepoint-reference": "TLI_110",
                "content": "also (.) wie [geSAGT;]"
            ]
        }
    }
}

【问题讨论】:

    标签: php xml simplexml


    【解决方案1】:

    不,它不会删除它们。这完美无瑕(有趣的应用程序顺便说一句):

    <?php
    $string = '<contribution speaker-reference="VK" start-reference="TLI_108" end-reference="TLI_111" parse-level="1">
        <unparsed>[JA:_a; ]<time timepoint-reference="TLI_109"/>ja,<time timepoint-reference="TLI_110"/>also (.) wie [geSAGT;]</unparsed>
    </contribution>';
    
    $xml = simplexml_load_string($string);
    $t = $xml->unparsed->time[0];
    print_r($t->attributes());
    ?>
    // output:
    SimpleXMLElement Object
    (
        [@attributes] => Array
            (
                [timepoint-reference] => TLI_109
            )
    
    )
    

    您甚至可以遍历它们:

    $times = $xml->unparsed->children();
    foreach ($times as $t) {
        $attributes = $t->attributes());
        // do sth. useful with them afterwards
    }
    

    提示:假设您在 xml 树上尝试 print_r()var_dump()。这有时会产生不透明的结果,因为大多数魔术都发生在幕后。最好使用echo $xml-&gt;asXML(); 来查看实际的 XML 字符串。

    【讨论】:

    • 你是对的。它不会删除它们,但它仍然不能像我预期的那样工作,或者更确切地说是希望它工作:D 我需要将三个字符串分开,但我认为这是该工具生成的 XML 的问题。
    猜你喜欢
    • 1970-01-01
    • 2011-01-27
    • 1970-01-01
    • 2011-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-15
    • 1970-01-01
    相关资源
    最近更新 更多