我有一个XML产品Feed,我正在使用PHP
进行解析,以将产品加载到database.
我需要将每个元素放入$products = array()
的数组中,例如:
$products[AttributeID] = value
这是我到目前为止所做的:
我使用的是simplexml,我已经掌握了大部分内容:
$xml = simplexml_load_file($CatalogFileName) or die("can't open file " . $CatalogFileName);
foreach($xml->children() as $products) {
foreach($products->children() as $product) {
$new_product = array();
$new_product[sku] = "AS-" . $product->Name;
foreach($product->Values->Value as $node) {
$node_name = preg_replace('/\s+/', '', $node[AttributeID]);
$new_product[$node_name] = $node[0]; **<--THIS IS NOT WORKING: $node[0] returns an array I only want the data in each attribute.**
}
foreach($product->AssetCrossReference as $node) {
$new_product[image] = "http://www.xxxxxxxx.com/images/items/fullsize/" . $node[AssetID] . ".jpg";
}
print_r($new_product);
}
}
以下是一个产品节点的图片:XML
有人可以在这里给我一些帮助吗?我做了很多PHP编程,但这是我第一次处理XML
答案 0 :(得分:0)
可能的解决方案是使用xpath方法查找<Value>
元素。
xpath
方法将返回SimpleXMLElement对象的数组。
这些SimpleXMLElement个对象有一个attributes方法,可用于访问“AttributeID”属性。
我希望这个例子可以帮到你:
$xml = simplexml_load_file($CatalogFileName) or die("can't open file " . $CatalogFileName);
$productsArray = array();
foreach($xml->children() as $products) {
foreach($products->children() as $product) {
$new_product = array();
$productId = (string)$product->attributes()->ID;
$new_product['NAME'] = "AS-" . (string)$product->Name;
// xpath will return an array of SimpleXMLElement objects
$values = $product->Values->xpath('//Value');
// use the attributes method to access the AttributeID
foreach ($values as $node) {
$attributeID = (string)$node->attributes()->AttributeID;
$new_product[$attributeID] = trim((string)$node);
}
$new_product['AssetID'] = sprintf(
"http://www.xxxxxxxx.com/images/items/fullsize/%s.jpg",
(string)$product->AssetCrossReference->attributes()->AssetID
);
// Add $new_product to $productsArray using the $productId as the array key
$productsArray[$productId] = $new_product;
}
}