PHP Parse XML issues when XML has variables
Pls see snippet of XML file below:
<products>
<product>
<id>2589527</id>
<name>Samsung PS42C450</name>
<manufacturer>Samsung</manufacturer>
<manufacturer-id>22</manufacturer-id>
<description>42 in, Widescreen, Plasma, HD Ready, Samsung DNIe+ ,</description>
<category>Sound and Vision > Vision > TVs</category>
<category-id>2</category-id>
<number-of-retailers>16</number-of-retailers>
<image-url height="217" width="300">http://images.pricerunner.com/product/300x217/101294172/Samsung-PS42C450.jpg</image-url>
<rating type="average">
<average>4,1</average>
</rating>
<rating type="professional">
<average>4,1</average>
<num-ratings>1</num-ratings>
</rating>
<lowest-price currency="GBP">354.44</lowest-price>
<highest-price cu开发者_JS百科rrency="GBP">549.00</highest-price>
</product>
</products>
I'm having problems parsing image-url, lowest-price and highest-price
I'm trying:
$lowprice = $products->lowest-price;
$highprice = $products->highest-price;
$imageURL = $products->image-url;
But they are returning nothing - any ideas what I'm doing wrong?
use $products->{'lowest-price'}. (with curly braces you can use special characters such as the minus sign)
Shai.
$products->lowest-price;
PHP will interpret as
($products->lowest) minus price;
There's no "lowest" in your $products object, and price
is almost certainly not a defined constant, so both show up as null, get cast to 0's, and end up producing 0-0=0
It's probably because of the dash (assuming other properties work). Try encapsulating them with curly braces, like
$products->{highest-price};
There are (maybe) two unrelated issues.
1. XML structure
Your (broken) code, e.g. $products->lowest-price
is wanting to access the lowest-price
element which is a child of $products
. Assuming the variable is named after the element, you have a little more work to do. The XML is structured like
<products>
└─ <product>
└─ <lowest-price>
So if $products
is the `products> element, then three steps are needed.
$products->product->lowest-price
The above may be a non-issue, and simply unfortunate variable naming.
2. Dash (-) in element name
When presented with $a->b-c
, PHP sees that as $a->b <minus> c
as b-c
is not a valid label (and no a valid object property name). As noted on the "SimpleXML Basic usage" manual page (link), the appropriate solution is to use the variable property syntax ala.
$products->product->{'lowest-price'}
See: http://php.net/simplexml.examples-basic (Example #3)
精彩评论