简体   繁体   中英

Extract some CDATA from a xml file with PHP

I've to extract some data from a xml file. In this file there are some tags that contains CDATA content and I don't try to extract this contents.

The file is like this:

<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>

I parse the xml file in this way:

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

My problem is tag. I try to extract the first only using this code:

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

but I don't try to extract every picture_url.

How can I parse all the pictures tag?

Many thank's!

you are looping over the wrong variable. what you need is:

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

(you can replace echo with whatever command you need)

Gilad almost had it!

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

https://3v4l.org/990NR

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM