【问题标题】:Looping through xml file images with 'simplexml' php使用 'simplexml' php 循环遍历 xml 文件图像
【发布时间】:2020-07-27 18:20:40
【问题描述】:

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

iam 使用简单的 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"> }?> 

【问题讨论】:

    标签: php xpath foreach element simplexml


    【解决方案1】:

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

    解决方案 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 }
    

    【讨论】:

    • 太棒了,谢谢。我设法让解决方案 2 与 /pictures/picture 一起工作(所以又深入了一点。不知道为什么我对解决方案 1 有运气。你知道任何更好的资源吗?我发现 php 站点几乎没用。所以烦人,因为您的解决方案显示我很接近,但我无法在任何地方找到“简单”资源
    猜你喜欢
    • 2013-11-02
    • 1970-01-01
    • 2011-10-13
    • 2011-05-07
    • 2023-03-26
    • 1970-01-01
    • 2021-11-12
    • 1970-01-01
    相关资源
    最近更新 更多