keenProgrammer
keenProgrammer

Reputation: 438

Trying to extract elements from XML and place into an Array

I've created a simple XML document that will hold information on numerous cities.

<?xml version="1.0" encoding="ISO-8859-1"?>
<config>
    <city>
        <id>London</id>
    </city>
    <city>
        <id>New York</id>
    </city>
</config>

I'm trying to extract the city elements and place them into an array. I have the following so far and the output is simply Array when I call the function.

<?php
$configFile = 'cityConfig.xml';

function getCityConfig($configFile) {

    $xml = new SimpleXmlElement(file_get_contents("cityConfig.xml"));

    $cities = array();

    $cityId = $xml->city[0]->id;
    array_push($cities, $cityId);
    $cityId = $xml->city[1]->id;
    array_push($cities, $cityId);

    //var_dump($cities); 

    return $cities;
}

//print_r(getCityConfig($configFile)); 
echo getCityConfig($configFile); 

?>

var_dump suggests that values are being added into the array.

array(2) { [0]=> object(SimpleXMLElement)#2 (1) { [0]=> string(6) "London" } [1]=> object(SimpleXMLElement)#4 (1) { [0]=> string(8) "New York" } } Array

I'm trying to achieve something along these lines.

$cities = array(
   'London',
    'New York',
    'Paris'
);

The array indexes are called in my index.php to display content.

$pageIntroductionContent = 'The following page brings twin cities together. Here you will find background information on  ' . $cities[0] . ', ' . $cities[1] . ' and ' . $cities[2] . '.';

Any ideas where I'm going wrong?

Thanks in advance.

Upvotes: 3

Views: 157

Answers (1)

lorenzo-s
lorenzo-s

Reputation: 17010

The fact is that in SimpleXMLElement object, all the data is represented as an object, including attributes (as your var_dump suggests, in fact). So, you can get strings by casting these object, because they implement a _toString() method I think. Try:

$cityId = (string) $xml->city[0]->id;

It should work.

Upvotes: 1

Related Questions