Delta_Cmdr
Delta_Cmdr

Reputation: 180

Simple XML & PHP

Hey there I have an XML file that contains some information similar to this:

<root>
 <library>
   <name>TestName1</name>
   <location>TestLocation1</location>
 </library>
 <library>
   <name>TestName2</name>
   <location>TestLocation2</location>
 </library>
 <book>
   <name>Book1</name>
   <author>Author1</author>
 </book>
 <book>
   <name>Book2</name>
   <author>Author2</author>
 </book>
</root>

what I did was create an array that would store an array of the information. However My problem lies with trying to return only books or libraries.

$xml = "libraries.xml";
$array_libraries = array();
$library = simplexml_load_file($xml);

foreach($library as $get_library) {
$name = $get_library->name;
$location = $get_library->location;
array_push($array_albums, array($name, $location));
}

I would like to keep books and libraries in the same file if possible but i only want to put libraries into the array, thank you in advance :-)

Upvotes: 1

Views: 117

Answers (3)

PatomaS
PatomaS

Reputation: 1603

This could be useful

$xml = "libraries.xml";
$array_libraries = array();
$array_albums = array();
$library = simplexml_load_file( $xml );

foreach( $library as $get_library => $x ) {
    $name = $x->name;
    $location = $x->location;
    if ( $get_library === 'library' ) {
        array_push( $array_libraries, array( $name, $location ) );
    }
    if ( $get_library === 'book' ) {
        array_push( $array_albums, array( $name, $location ) );
    }
}

If you only want the libraries, you keep only that if and remove/comment the other one, if you want both, then you already have an example working.

Bye

Upvotes: 0

SomeKittens
SomeKittens

Reputation: 39532

You'll need to loop over just the libraries, not just the whole XML.

Change:

foreach($library as $get_library) {

to

foreach($library->library as $get_library) {

As a side note, SimpleXML isn't the greatest for working with XML. Look into using DOMDocument instead.

Upvotes: 2

Jonathan Muller
Jonathan Muller

Reputation: 7516

You define an array,

$array_libraries = array();

Then you push in another array

array_push($array_albums, array($name, $location));

Try pushing in the previously declared array:

array_push($array_libraries, array($name, $location));

Upvotes: 0

Related Questions