1

I have a XML (simplified) like this:

<article>
    <title>My Article</title>
    <image src="someurl.jpg" />
    <image src="someotherurl.jpg" />
</article>

How do I select the <image> elements? They have the same name. To select the <title> i simply do this:

$xml = simplexml_load_file( "theurltomyxml.xml" );
$article = $xml->article;
$title = $article->title;

But how do I get the images? They have the same name! Just writing $article->image won't work.

2 Answers 2

2

I know this is an older question/answer but I had a similar issue and solved it by using the second solution by ajreal with a few adjustments of my own. I had a series of top level nodes (the xml was not formatted properly and didn't split the elements into parent nodes - out of my control). So I used a for loop that counts the elements then used ajreal's solution to echo back the contents I wanted with the iteration of $i.

My use was a bit different than above so I've tried to change it to make it more relevant to your images issue. Anyone please let me know if I made a mistake.

$campaigns = $xml->children();

for($i=0;$i<=$campaigns->count();$i++){
    echo $campaigns[$i]->article->title . $campaigns[$i]->article->image[0];
}
Sign up to request clarification or add additional context in comments.

Comments

0

You can do this :-

foreach ($xml->xpath("/article/image") as $img)
{
  ...
}

Or (is list of image node, so normal way of access array is workable)

$xml->image[0];
$xml->image[1];

2 Comments

The second solution: Yes it works but only if I always know the number of <image> elements. Which I don't. How would I do if the number of elements is unknown?
Use the first one with a loop

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.