0

I'm having some trouble saving some data after using PHP's simplexml_load_file function. I want to go through the SimpleXML Object and if the data meets the requierments I want to put it in an array. The problem is that I can't get the value of the fields, it seems to always pass the whole object through if that makes any sense.

Here my code

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);

And my output:

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 ) ) 
)

All I want to store is the actual value. How do I do that?

For reference here is a sample of my 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>
BFTrick
  • 5,211
  • 6
  • 24
  • 28

2 Answers2

3

SimpleXML does always return another SimpleXML object. You need to cast the return value to a string or number.

example:

$products["041132"]['sku'] = intval($allProducts->product[1]->sku); 
$products["041132"]['title'] = (string)$allProducts->product[1]->title; 
brian_d
  • 11,190
  • 5
  • 47
  • 72
  • or you could actually cast it like `$products["041132"]['sku'] = (integer) $allProducts->product[1]->sku;` which is faster and my personal preference :-) – prodigitalson Nov 08 '11 at 22:06
  • Or you could use strval too. Would actually suggest using strval for all because of the preceding zeros and strings are easily converted to integers if used as such. :) – mseancole Nov 08 '11 at 22:47
  • It's been a while since I had to cast anything. Thanks! – BFTrick Nov 09 '11 at 20:18
1

Try casting the elements as strings, e.g.:

$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."

Nick Shaw
  • 2,083
  • 19
  • 27