absentx
absentx

Reputation: 1417

How do I parse this XML with PHP

Normally the XML files I have to parse are like this:

<row id="1">
    <title>widget<title>
    <color>blue<color>
    <price>five<price>
</row>

Which I would then parse like this:

$xmlstr_widget = file_get_contents($my_xml_feed);
$feed_widget = new SimpleXMLElement($xmlstr_widget);

foreach($feed_widget as $name) {
    $title = $name->title;
    $color = $name->color;
    $price = $price->price;
  }

Works great! But now I have xml in a bit different format and I am a little stumped since I don't have a whole lot of xml parsing experience:

<Widget Title="large" Color="blue" Price="five"/>
<Widget Title="small" Color="red" Price="ten"/>

How do I drill into that a little further and get it parsed properly? I have tried a few things but no success.

So the problem is when I try something like below with the different xml feed, I cannot echo any results.

foreach($feed_widget as $name) {
    $title = $name->title;
    $color = $name->color;
    $price = $price->price;
  }

Upvotes: 1

Views: 88

Answers (4)

Jazzepi
Jazzepi

Reputation: 5480

<Widget Title="large" Color="blue" Price="five"/>

is short-hand for

<Widget Title="large" Color="blue" Price="five"></Widget>

The Title="large" Color="blue" etc are ATTRIBUTES of the XML tag. The foreach statement you've provided in the question extracts the CONTENTS of the XML tag (what appears between the opening and closing tags). You won't get anything that way because the CONTENTS are a string of zero length.

http://www.php.net/manual/en/simplexmlelement.attributes.php

Upvotes: 1

user142162
user142162

Reputation:

You can access the attributes like you would access elements in an associative array:

foreach($feed_widget as $name) {
    $title = $name['Title'];
    $color = $name['Color'];
    $price = $name['Price'];
}

Upvotes: 2

Alex Howansky
Alex Howansky

Reputation: 53553

You can use the attributes() method to get the list of attributes on an element:

foreach ($xml as $element) {
    foreach ($element->attributes() as $name => $value) {
        echo "$name = $value\n";
    }
}

Outputs:

Title = large
Color = blue
Price = five
Title = small
Color = red
Price = ten

Upvotes: 2

bobbiloo
bobbiloo

Reputation: 432

You need to use the attributes() of the element.

For example, you'd want to do

$feed_widget -> attributes() -> Color;

would give you "blue"

Resource: http://www.w3schools.com/xml/xml_attributes.asp

Upvotes: 1

Related Questions