PHP SimpleXML select attributes
I have an XML feed that looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<productFeed version="1.0" timestamp="20100910:04:06:55">
<product id="196">
<name>Lorem</name>
<price>190.00</price>
<description>Lorem Ipsum</description>
<pr开发者_Go百科oductURL> http://www.example.com</productURL>
<imageURL> http://www.example.com/lorem.jpg </imageURL>
<additional>
<field name="country" value="IT" />
<field name="region" value="Rome" />
<field name="city" value="Rome" />
</additional>
<categories>
<category name="foobar" />
</categories>
</product>
</productFeed>
I'm trying to print out the category attribute, among other things with this script:
<?php
$url = 'lorem.xml';
$xml = simplexml_load_file($url);
$expr = "/productFeed//product/additional/field[@value='Rome']/parent::*/parent::*";
$result = $xml->xpath($expr);
foreach($result as $item) {
echo $item->name;
echo $item->imageURL;
echo $item->description;
echo $item->price;
echo $item->category->attributes()->name;
}
This produces a:
Warning: main() [function.main]: Node no longer exists
error although the FireXPath Firebug plugin tells me I'm correctly selecting the attributes too.
You have a typo!
Its:
echo $item->categories->category->attributes()->name;
Not:
echo $item->category->attributes()->name;
For everything:
foreach($result as $item) { echo $item->name; echo $item->imageURL; echo $item->description; echo $item->price; echo $item->category->attributes()->name; foreach($item->additional->field as $field) { echo $field["name"]; echo $field["value"]; } }
Good Luck
精彩评论