使用PHP从xml文件中提取一些CDATA

时间:2019-05-06 13:57:32

标签: php xml simplexml

我必须从xml文件中提取一些数据。 在该文件中,有些标签包含CDATA内容,我不会尝试提取这些内容。

文件如下:

<treeplat>
<ad>
<id>965192-VR</id>
<region>VT</region>
<description>
<![CDATA[
Orte scalo. Vicinissimo alla stazione, in zona tranquilla e panoramica, proponiamo appartamento di recente costruzione così composto: ingresso, salone con ampio angolo cottura e balcone, disimpegno, camera matrimoniale con balcone, cantina e posto auto.
]]>
</description>
<pictures>
<picture>
<picture_url>
<![CDATA[
http://www.immobile.net/media/foto/1440/9f352078-885d-4281-a36d-1d22b3cbdcd9-x.jpg
]]>
</picture_url>
</picture>
<picture>
<picture_url>
<![CDATA[
http://www.immobile.net/media/foto/1440/992a5c0f-62dd-48f2-8c41-9b8ee9e06ca9-x.jpg
]]>
</picture_url>
</picture>
<picture>
<picture_url>
<![CDATA[
http://www.immobile.net/media/foto/1440/a61b4705-ed0a-494b-86fc-e92bb4c916e7-x.jpg
]]>
</picture_url>
</picture>
<picture>
<picture_url>
<![CDATA[
http://www.immobile.net/media/foto/1440/d1817d53-51fa-43dc-baf9-d3457963e694-x.jpg
]]>
</picture_url>
</picture>
<picture>
<picture_url>
<![CDATA[
http://www.immobile.net/media/foto/1440/8299cd3e-f253-4c83-9629-fb77131a2efb-x.jpg
]]>
</picture_url>
</picture>
</pictures>
</ad>
</treeplat>

我以这种方式解析xml文件:

$xml = simplexml_load_file(storage_path('app'.DIRECTORY_SEPARATOR.'public'.DIRECTORY_SEPARATOR.$percorso_file.'test.xml')); 
foreach ($xml->ad as $immobile) {
...
}

我的问题是标签。我尝试仅使用以下代码提取第一个:

$picture_url_1 = (string)$immobile->pictures->picture->picture_url

但我不会尝试提取每个picture_url。

如何解析所有图片标签?

非常感谢!

2 个答案:

答案 0 :(得分:1)

您正在遍历错误的变量。您需要的是:

$pictures = $xml->ad->pictures->picture;
foreach ($pictures as $picture) {
    echo $picture->picture_url;
}

(您可以使用所需的任何命令替换echo

答案 1 :(得分:0)

吉拉德(Gilad)差不多吃了!

$pictures = $xmlData->ad->pictures;
foreach($pictures as $picture)
{
   foreach($picture as $pic)
   {
      echo (string) $pic->picture_url;
   }
}

https://3v4l.org/990NR