如何读取没有<? xml ?>
标签的xml数据并将其转换为数组,
XML数据来自url,请参阅下面的XML数据:
<Item>
<itemID>140</itemID>
<systemSku readonly="true">210000000140</systemSku>
<defaultCost currency="USD">6.5</defaultCost>
<avgCost currency="USD">6.5</avgCost>
<tax>true</tax>
<archived>false</archived>
<itemType>default</itemType>
<description>Adult Baltic Amber - 17 inch - Raw Round Lemon Necklace</description>
<modelYear>0</modelYear>
<upc></upc>
<ean></ean>
<customSku>BANK-RL-17R</customSku>
<manufacturerSku></manufacturerSku>
<timeStamp>2013-11-09T09:32:42+00:00</timeStamp>
<categoryID>8</categoryID>
<taxClassID>0</taxClassID>
<departmentID>0</departmentID>
<itemMatrixID>0</itemMatrixID>
<manufacturerID>4</manufacturerID>
<seasonID>0</seasonID>
<defaultVendorID>0</defaultVendorID>
<Prices>
<ItemPrice>
<amount currency="USD">32.95</amount>
<useType readonly="true">Default</useType>
</ItemPrice>
<ItemPrice>
<amount currency="USD">0</amount>
<useType readonly="true">MSRP</useType>
</ItemPrice>
</Prices>
</Item>
我使用下面的代码php来读取数据:
<?php
//header('content-type: text/plain; charset=UTF-8');
mb_internal_encoding("UTF-8");
$url = "http://east6.merchantos.com/API/Account/59675/Item";
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url); // get the url contents
$output = curl_exec($ch); // execute curl request
curl_close($ch);
$total_product_item = simplexml_load_string('<?xml version="1.0" ?>' .$output);
$total_product_item = object_to_array($total_product_item);
$total_product_item = $total_product_item['Item'];
//$count_products_qty = count($total_product_item);
echo "<pre>"; print_r($total_product_item); echo "</pre>";
function object_to_array($data)
{
if ((! is_array($data)) and (! is_object($data))) return 'xxx'; //$data;
$result = array();
$data = (array) $data;
foreach ($data as $key => $value) {
if (is_object($value)) $value = (array) $value;
if (is_array($value))
$result[$key] = object_to_array($value);
else
$result[$key] = $value;
}
return $result;
}
?>
请帮帮我。 谢谢!
答案 0 :(得分:1)
如果我理解您的问题是正确的,那么缺少<?xml version="1.0" ?>
就是问题所在。在输出之前添加它,然后解析它:
$total_product_item = simplexml_load_string('<?xml version="1.0" ?>' . $output);