猿问

PHP如何以有序的方式打印节点值XML

我有一个这样的 XML:


<description>

    <heading id="01"> Math </heading>

    <p id="01"> Text 1 </p>

    <heading id="02"> History </heading>

    <p id="02"> Text 2</p>

    <p id="03"> Text 3</p>

    <heading id="03"> Biology </heading>

    <p id="04"> Text 4 </p>

</description>

我也有很多 xml 文件具有这样的结构,它们仅与<p>每个<heading>节点的节点数量不同。我怎样才能打印<heading>一些<p>节点和第二个标题....


我尝试使用 foreach,但事实并非如此。我的代码:


<?php

$xml=simplexml_load_file("NWB2.xml") or die("Error: Cannot create object");

echo "<b>".$xml->{'description'}->{'heading'}."</b>";

echo "<p>".$xml->{'description'}->{'p'}."</p>";

?>


繁花如伊
浏览 121回答 1
1回答

慕容森

如果只是根据输入标签的样式不同的情况,可以使用foreach()循环并根据标签类型输出值...$xml=simplexml_load_file("NWB2.xml") or die("Error: Cannot create object");foreach ( $xml as $type => $value )&nbsp; &nbsp; {&nbsp; &nbsp; if ($type == "p")&nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; echo $value;&nbsp; &nbsp; }&nbsp; &nbsp; else {&nbsp; &nbsp; &nbsp; &nbsp; echo "<b>$value</b>";&nbsp; &nbsp; }}
随时随地看视频慕课网APP
我要回答