使用 'simplexml' php 循环遍历 xml 个文件图像

Looping through xml file images with 'simplexml' php

用 Google 搜索了几个小时,但没有任何乐趣。

我使用简单的 xml 并对我的 xml 文件进行各种查询。我可以显示一张图片(1 张图片) 美好的。

我无法让 foreach 循环显示所有图像。好吧,我可以,但我使用了 [i++],它显示了所有图像,但不会停止循环!

下面显示 2 张图片。首先是显示 1 个图像的基本显示和我的理解。 第二张图片是我希望所有循环发生的地方。

$reference  = $_POST['varname'];
$xml =  simplexml_load_file('save.xml') or die("can not find file");
$result = $xml->xpath("//property[property_reference='$reference']");
foreach ( $result as $elements){
<img class="card-img-top" height='240px' width='340px' src=" <?php echo 
$elements->pictures->picture[0]->filename  ; ?> " alt="Card image cap"    > 
} ;  
<br>
<?php foreach( $elements as $image) { ?>
<img class="card-img-top" height='240px' width='340px' src=" <?php echo 
$elements->pictures->picture[All of the images]->filename ; ?> " alt="Card image cap"> }?> 

看起来你需要在你的结构中循环得更深,因为你有一个数组的数组。

解决方案 1:循环更深

<?php

$reference  = $_POST['varname'];
$xml = simplexml_load_file('save.xml') or die("can not find file");
$result = $xml->xpath("//property[property_reference='$reference']");
foreach ($result as $elements) {
    foreach ($elements as $pictures) {
        foreach ($pictures as $picture) { ?>
            <img class="card-img-top" height='240px' width='340px' src="<?php echo $picture->filename?> " alt="Card image cap"> 
        <?php }
    }
}

解决方案 2:使用更深层次的 XPath:

<?php

$reference  = $_POST['varname'];
$xml = simplexml_load_file('save.xml') or die("can not find file");
$pictures = $xml->xpath("//property[property_reference='$reference']/pictures");
foreach ($pictures as $picture) { ?>
    <img class="card-img-top" height='240px' width='340px' src="<?php echo $picture->filename?> " alt="Card image cap">
<?php }