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

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Browsers only know CSS so your awesome SASS code needs to be translated into normal CSS. Here I'll try to explain what you should aim for in order to take full advantage of SASS.
Have you tried to learn about Unicode, UTF-8, and multibyte text encoding and all the articles are just too "academic" or too technical? This article aims to make the whole topic easy for just about anyone to understand.
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
The viewer will learn how to count occurrences of each item in an array.

726 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