0

我有一个如下所示的 XML 文件:

<?xml version="1.0" encoding="ISO-8859-1"?>
<products>
  <product sku="CATDJ" type="CAT" vendor="DJ" active="1" on_sale="0" discountable="0">
    <name>CATALOGS</name>
    <short_description><![CDATA[The DJ catalog features 182 pages]]></short_description>
    <long_description><![CDATA[The DJ catalog features 182 pages.]]></long_description>
    <price>1.5</price>
    <stock_quantity>65</stock_quantity>
    <release_date>2003-05-06T00:00:00-04:00</release_date>
    <barcode>782421791315</barcode>
  </product>
  ....

我可以获取价格、库存数量和条形码,但不能获取 sku、活动或折扣数据。

这就是我的代码如下所示:

   $myinv = simplexml_load_file('http://www.*******.com/products.xml');
   foreach ($myinv as $invinfo):
     $sku = $invinfo->products->product->sku;
     $active = $invinfo->products->product->active;
     $deductible = $invinfo->products->product->discountable;
     $qty=$invinfo->stock_quantity;
     $price=$invinfo->price;
     $upc=$invinfo->barcode;

我究竟做错了什么?顺便说一句,我是 php 新手。

谢谢您的帮助。

4

2 回答 2

1

我总是对从 SimpleXML 获得的所有内容进行类型转换,因为它总是返回一个 SimpleXMLElement。var_dump你的变量自己看看。

<?php

$xml = '<?xml version="1.0" encoding="ISO-8859-1"?>
<products>
  <product sku="CATDJ" type="CAT" vendor="DJ" active="1" on_sale="0" discountable="0">
    <name>CATALOGS</name>
    <short_description><![CDATA[The DJ catalog features 182 pages]]></short_description>
    <long_description><![CDATA[The DJ catalog features 182 pages.]]></long_description>
    <price>1.5</price>
    <stock_quantity>65</stock_quantity>
    <release_date>2003-05-06T00:00:00-04:00</release_date>
    <barcode>782421791315</barcode>
  </product>
</products>';

$myinv = new SimpleXMLElement($xml);

$products = $myinv->product;
foreach ($products as $product){

    $attrs = $product->attributes();
    $sku = $attrs->sku;
    $active = $attrs->active;
    $discountable = $attrs->discountable;
    $qty = $product->stock_quantity;
    $price = $product->price;
    $upc = $product->barcode;

    echo (string)$sku . "<br>\n";
    echo (string)$active . "<br>\n";
    echo (string)$discountable . "<br>\n";
    echo (string)$qty . "<br>\n";
    echo (string)$price . "<br>\n";
    echo (string)$upc . "<br>\n";
}
?>
于 2013-02-04T20:15:30.390 回答
0

XPath 可以完成获取属性值的工作$xpath->query("//product[@name='sku']/@value");

于 2013-02-04T20:15:09.593 回答