I have loaded a xml file and I want a specific node when a child node exists.
For example: if the supplierItem->supplier->id is "0101" I want to get the stock "1" out of this specific supplierItem. So I need the parent stock node of the specific supplier id.
My xml looks something like this
<product>
<supplierItem>
<id>0001</id>
<supplier>
<id>0101</id>
<name>Company_1</name>
</supplier>
<supplierItemId>Product_1_ID</supplierItemId>
<productName>Product_1</productName>
<stock>1</stock>
</supplierItem>
<id>0002</id>
<supplier>
<id>0202</id>
<name>Company_2</name>
</supplier>
<supplierItemId>Product_1_ID</supplierItemId>
<productName>Product_1</productName>
<stock>2</stock>
</supplierItem>
<id>0003</id>
<supplier>
<id>0303</id>
<name>Company_3</name>
</supplier>
<supplierItemId>Product_1_ID</supplierItemId>
<productName>Product_1</productName>
<stock>3</stock>
</supplierItem>
</product>
My first attemp were:
$stocks = $xml->xpath("/product/supplierItem");
foreach ($stocks as $stock)
{
echo($stock); // get all stocks
}
Any idea? I stuck with it... Thanks in advance
You need to read up about Xpath. It can do that easily and a lot more:
Fetch supplierItem
nodes...
/product/supplierItem
... With a child node id
...
/product/supplierItem[id]
... that equals '0101' ...
/product/supplierItem[id = "0101"]
... and fetch the stock
element node from it:
/product/supplierItem[id = "0101"]/stock
SimpleXMLElement::xpath()
can only return arrays of nodes, but Xpath itselfs allows even to fetch the value directly. In PHP that is possible with DOMXpath::evaluate()
:
$stock = $domXpath->evaluate('string(/product/supplierItem[id = "0101"]/stock)')