Christian Isai
Christian Isai

Reputation: 146

using simplexml objects inside an array

I have the following code for getting a XML and making an array so I can update via an API:

$data1 = file_get_contents('neworderexample.xml');
$xml = new SimpleXMLElement($data1,LIBXML_NOCDATA);

foreach($xml -> Product as $ord){
$sku = $ord -> StockNumber;
$title = $ord -> Title;
$retail_price = $ord -> RRP;
$price = $ord -> SellPrice;
$description = $ord -> Description;
$inventory_level = $ord -> StockLevel;
$weight = $ord -> Weight;
$width = $ord -> Width;
$prodheight = $ord -> Height;
$depth = $ord -> Depth;

$fields = array(
"sku" => $sku,
"name" => $title,
"retail_price" => $retail_price,
"price" => $price,
"description " => $description,
"inventory_level " => $inventory_level,
"type" => "physical",
"availability" => "available",
"weight" => $weight,
"width" => $width,
"prodheight" => $prodheight,
"depth" => $depth,
"categories" => "1"
);

print_r ($fields);  

When I echo any variable I get just the value, but when I print the array I get the following:

[inventory_level ] => SimpleXMLElement Object ( [0] => 9 ) 
[type] => physical 
[availability] => available 
[weight] => SimpleXMLElement Object ( [@attributes] => Array ( [unit] => g ) [0] => 0.0 ) 
[width] => SimpleXMLElement Object ( [@attributes] => Array ( [unit] => (mm) ) [0] => 0 ) 
[prodheight] => SimpleXMLElement Object ( [@attributes] => Array ( [unit] => (mm) ) [0] => 0 ) 
[depth] => SimpleXMLElement Object ( [@attributes] => Array ( [unit] => (mm) ) [0] => 0 ) 
[categories] => 1 ) 

How can I get only the values in the array?

Upvotes: 0

Views: 178

Answers (2)

mlantz
mlantz

Reputation: 113

The issue arises in the fact that the SimpleXMLElement creates objects. Try converting those specific elements into integers/floats/string.

ex.

$fields = array(
"sku" => intval($sku),
"name" => $title,
"retail_price" => $retail_price,
"price" => $price,
"description " => $description,
"inventory_level " => $inventory_level,
"type" => "physical",
"availability" => "available",
"weight" => floatval($weight[0]).$weight['unit'],
"width" => intval($width[0]).$width['unit'],
"prodheight" => intval($prodheight[0]).$prodheight['unit'],
"depth" => intval($depth[0]).$depth['unit'],
"categories" => "1"
);

Try that it may work. I'm not too sure didn't run any tests myself.

Upvotes: 0

hakre
hakre

Reputation: 197659

Cast to string, e.g. use:

"sku" => (string) $sku,
         ^ ^ ^ ^ 

(this is more a comment than an answer and it will be deleted with the question which is a duplicate)

Upvotes: 1

Related Questions