使用php的SimpleXMLItterator按顺序打印子元素
Using php's SimpleXMLItterator to print sub elements in order
我正在处理以下问题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
这让我无法将它们组合成一个常规段落,中间使用斜体文本。我怎样才能做到这一点?
您可以使用 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
但是,如果将常规文本包含在某些标签中,会更容易。
我正在处理以下问题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
这让我无法将它们组合成一个常规段落,中间使用斜体文本。我怎样才能做到这一点?
您可以使用 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
但是,如果将常规文本包含在某些标签中,会更容易。