simpleXML accessing attributes

Hello,

I'm developing a site using simpleXML and so far have not had any problems. However I now need to access an attribute.

My normal way of accessing the XML is like this;

$xml = simplexml_load_file("xml/whats-on-blog.xml");

foreach($xml->gallery as $entry) {
 
}

I've now got to a point where I need to access some tag's attributes. My XML is as below. I would like to be able to change my foreach loop so that it only loops through image <items> with a gallery attribute of 1

How can this be done?
<?xml version="1.0" encoding="utf-8"?>
<galleries>
 
  <gallery id="1">
    <title>Sample Title 1</title>
  </gallery>
 
  <gallery id="2">
    <title>Sample Title 2</title>
  </gallery>
 
  <image gallery="1" id="1" sort="0">
    <src>image1.jpg</src>
  </image>
 
  <image gallery="1" id="2" sort="5">
    <src>image1.jpg</src>
  </image>
 
  <image gallery="1" id="3" sort="10">
    <src>image1.jpg</src>
  </image>
 
  <image gallery="2" id="4" sort="15">
    <src>image1.jpg</src>
  </image>
 
</galleries>

Open in new window

LVL 3
Mr_SplashAsked:
Who is Participating?
 
Ali KayahanConnect With a Mentor Full Stack DeveloperCommented:
    $entry['id']
0
 
Mr_SplashAuthor Commented:
Thanks for your reply, however that's returning everything between the <galleries> tags.
0
 
Mr_SplashAuthor Commented:
Sorry, I used $entry['1'] I thought you literally meant replace with id.

I've changed it to foreach($xml as $entry['id']) However it's still not working.
0
 
Mr_SplashAuthor Commented:
Ok, figured this out.
foreach($xml as $entry) {
  $gallery = $entry['gallery'];
  if ($gallery == 1) {
    echo $entry->src.'<br />';
  }
}

Open in new window

0
 
hernst42Commented:
Try this code:
foreach($xml->image as $entry) {
  echo $entry{'id'};
 
}

Open in new window

0
All Courses

From novice to tech pro — start learning today.