我想解析一个名为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;]"
]
}
}
}
答案 0 :(得分:0)
不,它不会删除它们。这完美无缺(有趣的应用程序顺便说一句):
<?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->asXML();
来查看实际的XML字符串。