我正在处理以下XML:
<Paragraph>This is a test. This is a test.
<Italic>This is an italicized test</Italic>
This is more tests
</Paragraph>
我试图引入XML,将其修改为文本字符串或HTML代码,并将其吐出来。我遇到了一个问题,我认为没有办法让所有这些文字保持正确的顺序。这是我的代码:
$xml = "<Paragraph>This is a test. This is a test.
<Italic>This is an italicized test</Italic>
This is more tests
</Paragraph>";
$itterator = new SimpleXmlIterator($xml);
$non_italicized = $itterator->__toString();
for ($itterator->rewind(); $itterator->valid(); $itterator->next()) {
$italicized = $itterator->current()->__toString();
}
$ non_italicized的输出:
This is a test. This is a test.
This is more tests
$斜体的输出:
This is an italisized test
这使我无法将它们组合在一个常规段落中,中间带有斜体文本。我怎样才能做到这一点?
答案 0 :(得分:2)
您可以使用DOM执行此操作:
$doc = new DOMDocument();
$doc->loadXML($xml);
foreach ($doc->childNodes->item(0)->childNodes as $i) {
echo "Element is: " . $i->nodeName . " Value is: " . trim($i->nodeValue) . "\n";
}
输出将是:
Element is: #text Value is: This is a test. This is a test.
Element is: Italic Value is: This is an italicized test
Element is: #text Value is: This is more tests
但是,如果常规文本包含在某些标记中会更容易。