phpmultidimensional-array

Convert multidimensional object from SimpleXML to a 2d array


I'm using SimpleXML to extract images from a public feed @ Flickr. I want to put all pulled images into an array, which I've done:

$images = array();
foreach($channel->item as $item){
    $url = $path->to->url;
    $images[] = $url;
}

From this I can then echo out all the images using:

foreach($images as $image){
    //output image
}

I then decided I wanted to have the image title as well as the user so I assumed I would use:

$images = array();
foreach($channel->item as $item){
    $url = $path->to->url;
    $title = $path->to->title;
    $images[$title] = $url;
}

I thought this would mean by using $image['name of title'] I could output the URL for that title, but it gives an Illegal Offset Error when I run this.. and would only have the title and url, but not the user.

After Googling a bit I read you cannot use _ in the array key, but I tried using:

$normal = 'dddd';
$illegal = '  de___eee';
$li[$normal] = 'Normal';
$li[$illegal] = 'Illegal';

And this outputs right, ruling out _ is illegal in array keys (..I think).

So now I'm really confused why it won't run, when I've used print_r() when playing around I've noticed some SimpleXML objects in the array, which is why I assume this is giving an error.

The ideal output would be an array in the format:

$image = array( 0 => array('title'=>'title of image',
                           'user'=>'name of user',
                           'url' =>'url of image'),
                1 => array(....)
         );

Solution

  • $images = array();
    foreach ($channel->item as $item){
        $images[] = array(
            'title' => $item->path->to->title,
            'url'   => $item->path->to->url
        );
    }
    
    foreach ($images as $image) {
        echo "Title: $image[title], URL: $image[url]\n";
    }