我的 xml 结构如下所示,我想用 php 遍历 xml 并匹配产品 id 属性。如果我得到匹配项,我想将产品元素添加到数组中并从函数中返回它们。
<Includes>
<Products>
<Product id="11348613">
<name>Product A</name>
<description>Product A's description</description>
<image>http://www.domain.com/images/productA.jpg</image>
</Product>
<Product id="11348614">
<name>Product B</name>
<description>Product B's description</description>
<image>http://www.domain.com/images/productB.jpg</image>
</Product>
</Products>
</Includes>
到目前为止,我的代码如下所示,这不是很有效,因为我认为我不了解如何匹配属性然后返回元素。你能指出我哪里出错了吗?
function lookupSkuFromProdId($ProductId) {
$reviewsXML = simplexml_load_file('reviews.xml');
foreach ($reviewsXML->Includes->Products->attributes() as $sku) {
if ($sku == $ProductId) {
$skuData = array();
$skuData[name] = $sku->name;
$skuData[description] = $sku->description;
$skuData[image] = $sku->image;
}
return $skuData;
}