SimpleXml和php Iteration

时间:2014-11-29 02:45:19

标签: php xml iteration simplexml

我一直在看这里发布的关于这个主题的其他问题,但他们似乎都有一个共同的对称" xml文件。

我先致电:

$xml_testimonials=simplexml_load_file("bck/testimonials.xml");

我无法迭代此文件:

<?xml version="1.0" encoding="utf-8"?>

<testimonials>

<description><![CDATA[
<p>Give us your feeback!</p>
 ]]></description>

<testimonials_collection>

<testimonial>
<testimonial_name>
Dummy Name
</testimonial_name>
<testimonial_content>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nec libero venenatis, posuere massa     vitae, volutpat massa. Maecenas placerat ac metus ut pulvinar.
</testimonial_content>
</testimonial>

<testimonial>
<testimonial_name>
Dummy Name
</testimonial_name>
<testimonial_content>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nec libero venenatis, posuere massa     vitae, volutpat massa. Maecenas placerat ac metus ut pulvinar.
</testimonial_content>
</testimonial> 

<testimonial>
<testimonial_name>
 Dummy Name
</testimonial_name>
<testimonial_content>
 Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nec libero venenatis, posuere massa vitae, volutpat massa. Maecenas placerat ac metus ut pulvinar.
 </testimonial_content>
 </testimonial>

 </testimonials_collection>

 </testimonials>

我试图使用:

foreach($xml_testimonials->testimonials->testimonials_collection as $testimonial) {
    print $testimonial->testimonial->testimonial_name;
}

我正在

Warning: Invalid argument supplied for foreach()

还有,我可以避免使用和保留html标签吗?

1 个答案:

答案 0 :(得分:1)

您的XML确实正确加载和解析,但是在使用SimpleXML时,XML文档的根节点未在结果对象结构中表示。这意味着不是使用<testimonials>(此处为根节点)开始遍历,而是访问的最高级别实际上是<testimonials_collection>

所以你的循环应该看起来像:

// Iterate <testimonial> nodes beneath <testimonials_collection>
foreach($xml_testimonials->testimonials_collection->testimonial as $testimonial) {
    // And get internal details of each <testimonial> node...
    echo $testimonial->testimonial_name;
}

这是一个演示,从3个节点检索Dummy Namehttp://codepad.viper-7.com/rQZwOJ