【问题标题】:Parsing and XML product feed解析和 XML 产品提要
【发布时间】:2015-12-05 19:35:24
【问题描述】:

我有一个 XML 产品提要,我正在使用 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

【问题讨论】:

标签: php xml xml-parsing


【解决方案1】:

您可以使用DOMDocument.loadXML()DOMDocument.getElementsByTagName()

$doc = new DOMDocument();
$doc->loadXML( "<your-xml/>" );

$products = [];
foreach ( $doc->getElementsByTagName( "Product" ) as $el ) {
    $p = handleProduct( $el );   
    $products[ $p->id ] = $p;
}

function handleProduct( DOMElement $el ) {
   return (object) [
       "ID" => $el->getAttribute( "ID" ),
       ....
   ];
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-17
    • 2014-10-29
    • 2012-02-13
    • 2012-10-19
    • 2012-02-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多