0

使用 PHP 的 simplexml_load_file 函数后,我在保存一些数据时遇到了一些麻烦。我想通过 SimpleXML 对象,如果数据满足要求,我想把它放在一个数组中。问题是我无法获得字段的值,如果有意义的话,它似乎总是通过整个对象。

这是我的代码

echo $allProducts->product[1]->sku."<br/>";
echo $allProducts->product[1]->title."<br/>";
echo $allProducts->product[1]->price."<br/>";
$products["041132"]['sku'] = $allProducts->product[1]->sku; 
$products["041132"]['title'] = $allProducts->product[1]->title; 
$products["041132"]['price'] = $allProducts->product[1]->price; 
print_r($products);

我的输出:

041132
Audrey Dining Chair
195.00
Array ( [041132] => Array ( 
  [sku] => SimpleXMLElement Object ( [0] => 041132 ) 
  [title] => SimpleXMLElement Object ( [0] => Audrey Dining Chair ) 
  [price] => SimpleXMLElement Object ( [0] => 195.00 ) ) 
)

我要存储的只是实际值。我怎么做?

以下是我的 XML 示例供参考:

<products>
  <product>
    <sku>934896</sku>
    <title>Savannah Barstool</title>
    <price>475.00</price>
  </product>
  <product>
    <sku>041132</sku>
    <title>Audrey Dining Chair</title>
    <price>195.00</price>
  </product>
</products>
4

2 回答 2

3

SimpleXML 总是返回另一个 SimpleXML 对象。您需要将返回值转换为字符串或数字。

例子:

$products["041132"]['sku'] = intval($allProducts->product[1]->sku); 
$products["041132"]['title'] = (string)$allProducts->product[1]->title; 
于 2011-11-08T22:03:45.530 回答
1

尝试将元素转换为字符串,例如:

$products["041132"]['title'] = (string)$allProducts->product[1]->title;

According to the PHP manual for SimpleXML (see here), "...to compare an element or attribute with a string or pass it into a function that requires a string, you must cast it to a string using (string). Otherwise, PHP treats the element as an object."

于 2011-11-08T22:06:37.917 回答