find xml element by attribute using php

Posted on 2008-06-11
Last Modified: 2008-06-22
I'm trying to read an xml file and replace a specific element data by using attribute id.

that's the xml structure:
<image id="4">
  <proName>Trake jeep8</proName>
  <upLine>PRODUCT #123543</upLine>
  <downLine>AGE 5 yrs, up</downLine>
  <textFileToload>Trake jeep8.txt</textFileToload>

The following code always replace the first element and not the one i need!
How should i fix it?


foreach ($xml->image as $image) {
  if ($xml->image->attributes("id")==$id){
     if ($video)
     if ($picture)

Open in new window

Question by:tzvio
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
LVL 34

Accepted Solution

Beverley Portlock earned 500 total points
ID: 21786749
Try altering the code like this

$id = 4
foreach ($xml->image as $image) {
  if ($image["id"]==$id){
     if ($video)
     if ($picture)

The ID attribute is returned in an array and as such needs [] rather than ()

There is an additional problem you should be aware of. If you are using PHP4 then the FOREACH will duplicate each piece of data and updating the duplicate has no effect. See here

(See joaohbruni's comment) -----

My original code only worked in PHP5:

foreach($array as $element) {
  $element->property = "new_value";

Solution for both PHP4 and PHP5:

while (list($key, $value) = each($array)) {
  $element =& $array[$key];
  $element->property = "new_value";

Author Comment

ID: 21787636
i don't need that code anymore
thanks anyway

Featured Post

Monthly Recap

May was a big month for new releases from Linux Academy! Take a look at what our team built recently in our blog. You can access the newest releases from our blog.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article discusses four methods for overlaying images in a container on a web page
Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
The viewer will receive an overview of the basics of CSS showing inline styles. In the head tags set up your style tags: (CODE) Reference the nav tag and set your properties.: (CODE) Set the reference for the UL element and styles for it to ensu…
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

688 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question