Trouble with PHP Simple XML
-
24-02-2021 - |
Question
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>
Solution
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;
OTHER TIPS
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."