2017-08-01 119 views
0

我想只選擇指定倉庫來更新庫存。 I.E.我想只有99,但是每個項目有不同數量的倉庫所以下面的代碼只能在99倉庫工作在第3行:使用simplexml按屬性選擇項目

$quantity_calc = $this_product->stock[2]; 

這裏的示例XML:

<product sku="123546" supplier="BOSCH" price="1.71"> 
<stock warehouse="SAND">2.00</stock> 
<stock warehouse="44">2.00</stock> 
<stock warehouse="55">4.00</stock> 
<stock warehouse="77">2.00</stock> 
<stock warehouse="88">2.00</stock> 
<stock warehouse="97">2.00</stock> 
<stock warehouse="99">2.00</stock> 
<stock warehouse="33">2.00</stock> 
</product> 

和print_r的($ this_product - >股票);

[@attributes] => Array 
     (
      [warehouse] => SAND 
     ) 

    [0] => 2.00 
    [1] => 2.00 
    [2] => 4.00 
    [3] => 2.00 
    [4] => 2.00 
    [5] => 2.00 
    [6] => 2.00 
    [7] => 2.00 
) 
+0

你真正想要什麼?選擇'stock'元素的倉庫=「99」'? –

+0

是的,但倉庫「99」並不總是在同一個地方。 – JoeDoe

回答

1

要獲取DOM的一部分,請使用Xpath表達式。 SimpleXMLElement::xpath()可以訪問它:

$product = new SimpleXMLElement($xml); 
var_dump(
    (string)$product->xpath('//stock[@warehouse=99]')[0] 
); 

DOM擴展本身已經爲它的DOMXpath類:

$document = new DOMDocument(); 
$document->loadXml($xml); 
$xpath = new DOMXpath($document); 

var_dump(
    $xpath->evaluate('string(//stock[@warehouse=99])') 
);