第一个xml
<response status="ok">
<Product>
<name>blbla</name>
<productGroupPrimary>test2</productGroupPrimary>
<productGroupSecondary>test</productGroupSecondary>
<purchasePrice>18</purchasePrice>
<retailPrice>29</retailPrice>
<status>active</status>
<productCode>0001</productCode>
</Product>
<Product>
...
</Product>
其他xml<response status="ok">
<StockQuantityInfo productCode="0001" quantityOnStock="5"></StockQuantityInfo>
<StockQuantityInfo productCode="dhzh" quantityOnStock="5"></StockQuantityInfo>
...
</response>
现在我想使用php使最终的XML文档看起来像这样
<response status="ok">
<Product>
<name>blbla</name>
<productGroupPrimary>test2</productGroupPrimary>
<productGroupSecondary>test</productGroupSecondary>
<purchasePrice>18</purchasePrice>
<retailPrice>29</retailPrice>
<status>active</status>
<productCode>0001</productCode>
<stock>5</stock>
</Product>
<Product>
...
</Product>
</response>
我不知道我怎么能做这个,我是一个初学者
foreach ($xml2->Product as $item2) {
$koda2=$item2->productCode;
foreach ($xml3->StockQuantityInfo as $item3) {
$koda3=$item3->productCode;
if ($koda2 ==$koda3 ) {
$zaloga=$item3->quantityOnStock;
$Product=$xml2->Product->addChild('zaloga',$zaloga);
}
}
结果是它没有对我做任何事情,没有变化,我有一个错误的地方,或者我在错误的方向思考
我建议使用DOM(而不是SimpleXML)。DOMXpath::evaluate()
允许您直接使用表达式获取产品的数量。
// bootstrap the documents
$products = new DOMDocument();
$products->loadXML($productsXML);
$productsXpath = new DOMXpath($products);
$stocks = new DOMDocument();
$stocks->loadXML($stockXML);
$stocksXpath = new DOMXpath($stocks);
// iterate the "Product" elements
foreach ($productsXpath->evaluate('//Product') as $product) {
// get the product code
$code = $productsXpath->evaluate('string(productCode)', $product);
// get the quantity of from the stocks response
$expression = 'number(//StockQuantityInfo[@productCode="'.$code.'"]/@quantityOnStock)';
$quantity = $stocksXpath->evaluate($expression);
// output expression and result for demonstration purposes
var_dump(
$expression, $quantity
);
// validate quantity is a number
if (!is_nan($quantity)) {
// append to "Product"
$product
->appendChild(
$products->createElement('Stock')
)
->textContent = $quantity;
}
}
echo "n", $products->saveXML();
输出:
string(65) "number(//StockQuantityInfo[@productCode="0001"]/@quantityOnStock)"
float(5)
<?xml version="1.0"?>
<response status="ok">
<Product>
<name>blbla</name>
<productGroupPrimary>test2</productGroupPrimary>
<productGroupSecondary>test</productGroupSecondary>
<purchasePrice>18</purchasePrice>
<retailPrice>29</retailPrice>
<status>active</status>
<productCode>0001</productCode>
<Stock>5</Stock></Product>
</response>