dongyin2390 2015-06-04 19:10
浏览 101
已采纳

使用php SimpleXMLIterator按顺序打印子元素

I am dealing with the following XML:

<Paragraph>This is a test. This is a test.
<Italic>This is an italicized test</Italic>
This is more tests
 </Paragraph>

I'm trying to pull in the XML, modify it as a text string or HTML code, and spit it back out. I'm running into the issue that I see no way of keeping all this text in its correct order. This is my code:

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

The output of $non_italicized:

 This is a test. This is a test.
 This is more tests

The output of $italicized:

This is an italisized test

This leaves me no real of way of combinging them together in a regular paragraph with italicized text in the middle. How can I achieve this?

  • 写回答

1条回答 默认 最新

  • dongsuichi6529 2015-06-04 19:44
    关注

    You can do this with 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) . "
    ";
    }
    

    The output will be:

    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
    

    However, it will be easier if the regular text is enclosed in some tags.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 vue3+electron打包获取本地视频属性,文件夹里面有ffprobe.exe 文件还会报错这是什么原因呢?
  • ¥20 用51单片机控制急停。
  • ¥15 孟德尔随机化结果不一致
  • ¥15 在使用pyecharts时出现问题
  • ¥15 深度学习残差模块模型
  • ¥50 怎么判断同步时序逻辑电路和异步时序逻辑电路
  • ¥15 差动电流二次谐波的含量Matlab计算
  • ¥15 Can/caned 总线错误问题,错误显示控制器要发1,结果总线检测到0
  • ¥15 C#如何调用串口数据
  • ¥15 MATLAB与单片机串口通信