【问题标题】:Elements from xml using php使用 php 来自 xml 的元素
【发布时间】:2017-04-01 10:12:41
【问题描述】:

所以我可以使用

访问 xml 文件及其所有元素
$xml = simplexml_load_file('file.xml');

里面有物品,其中一些有图像,一些比其他更多。当然,我从另一台服务器接收此文件。这些图像位于一个名为“images”的元素中,xml 文件如下所示:

<images>
    <image id="1" time_modif="1490197696"> 
        *** url here   ***
    </image >
    <image id="2" time_modif="1490197699">
        *** url here   ***
    </ image >
    <image id="3" time_modif="1490197702">
        *** url here   ***
    </image >
</images >

我迫切需要遍历这些图像并获取它们的 URL。为此我已经尝试过:

$element = $xml->element;
$i = 0;


foreach ($element->images as $img) 
{
    echo $img->image[$i] . '<br>';
    $i++
}

但是'foreach'循环只返回第一个url,而不返回其他的。

有人有什么想法吗?

提前致谢!

【问题讨论】:

    标签: php xml foreach


    【解决方案1】:

    @martin,您能否给出 中的一个图像元素的完整结构,因为我相信您正在尝试直接从 XML 文件加载。

    同时,我建议您阅读以下内容以获取帮助

    这将向您展示如何访问所需的项目通知数组。

    希望对你有帮助

    【讨论】:

    • 这对我有用!谢谢你的帮助 ! ` $xml = simplexml_load_file('file.xml'); $bien = $xml->bien[0]; foreach($bien->images->children() as $child) { echo $child . "
      "; } `
    【解决方案2】:

    你在找这个吗?

    PHP code demo

    <?php
    $domObject= new DOMDocument();
    $domObject->loadXML('<images>
        <image id="1" time_modif="1490197696"> 
            http://example.com/1.jpg
        </image >
        <image id="2" time_modif="1490197699">
            http://example.com/2.jpg
        </image>
        <image id="3" time_modif="1490197702">
            http://example.com/3.jpg
        </image >
    </images >');
    
    foreach($domObject->getElementsByTagName("image") as $nodeObj)
    {
        $imageLink=trim($nodeObj->nodeValue);
        print_r($imageLink);
    }
    

    【讨论】:

      【解决方案3】:

      好的 - 对于我的示例,我已将其更改为“load_string”,但这很好用。我认为您可能过于复杂了?

      $file = '
      <images>
          <image id="1" time_modif="1490197696"> 
             http://www.image123.com
          </image>
          <image id="2" time_modif="1490197699">
              http://www.image234.com
          </image>
          <image id="3" time_modif="1490197702">
              http://www.image456.com
          </image>
      </images >';
      
      $xml = simplexml_load_string($file);
      
      foreach ($xml as $img) 
      {
          echo $img.'<br>';
      }
      

      输出:

      http://www.image123.com

      http://www.image234.com

      http://www.image456.com

      【讨论】:

      • 你是对的,这可行,但如果是硬编码的话。如果我从 xml 文件中加载这些元素,它就不起作用
      【解决方案4】:
       foreach ($element->images as $img) { echo $img->image[$i] . '<br>'; $i++ }
      

      没有声明 image[ ] 数组,所以试试吧

      echo $img;
      

      它必须循环遍历它

      【讨论】:

      • 可能是,但您首先尝试的数组仍未声明,请尝试另一个
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多