Skip to content
Advertisement

How to delete in an XML document, a specific element according to the value of the child using PHP

    <response status="ok">
        <Product>
            <allowChangeOfPriceOnTheInvoice>true</allowChangeOfPriceOnTheInvoice>
            <allowChangeOfProductDescriptionOnTheInvoice>true</allowChangeOfProductDescriptionOnTheInvoice>
            <allowChangeOfVatRateOnTheInvoice>false</allowChangeOfVatRateOnTheInvoice>
            <costPosition></costPosition>
            <currency>EUR</currency>
            <description>tralala ko imam</description>
            <exchangeRate>SlovenianBankMiddleRate</exchangeRate>
            <grossPrice>22.13</grossPrice>
            <isTrackedByLotNumbers>false</isTrackedByLotNumbers>
            <lastUpdateTimestamp>30.01.2021 17:07:34</lastUpdateTimestamp>
            <name>3D očala Philips PTA508</name>
            <onlineShopVisibility>notVisibleOnline</onlineShopVisibility>
            <procurementTransactionAccount>660000</procurementTransactionAccount>
            <productCode>3D OCALA 1</productCode>
            <productGroupPrimary></productGroupPrimary>
            <productGroupSecondary></productGroupSecondary>
            <retailPrice>27</retailPrice>
            <status>active</status>
            <trackItemsBySerialNumbers>false</trackItemsBySerialNumbers>
            <type>goodsWithStockManagement</type>
            <unit>kos</unit>
            <useOfPriceList>false</useOfPriceList>
            <vatPercentage>22</vatPercentage>
            <warrantyPeriod>0</warrantyPeriod>
        </Product>
<Product>
...
<onlineShopVisibility>VisibleOnline</onlineShopVisibility>
...
</Product>
</response>

notVisibleOnline

How to delete all elements in a xml Product, if the element <onlineShopVisibility> value notVisibleOnline

I really need to delete all Product that contain <onlineShopVisibility>notVisibleOnline</onlineShopVisibility>

and save to a new file

Code so far (copied from comment)…

$toDelete = array ();
foreach ( $data1->Product as $item ) {
    $price = $item->onlineShopVisibility; 
    if ($price ="notVisibleOnline" ) { 
        $toDelete[] = $item; 
    } 
} 
foreach ($toDelete as $item) { 
    $dom = dom_import_simplexml($item); 
    $dom->parentNode->removeChild($dom); 
} 
echo $data1; 
file_put_contents('artikli.xml', $data1);

Advertisement

Answer

You’re converting each node to DOM. However you could use DOM directly.

// bootstrap the DOM 
$document = new DOMDocument();
$document->load($xmlFile);

// fetch nodes using an xpath expression 
$xpath = new DOMXpath($document);
$products = $xpath->evaluate('//Product[onlineShopVisibility="notVisibleOnline"]');

// iterate nodes
foreach ($products as $product) {
    // remove node
    $product->parentNode->removeChild($product);
}

$document->save($xmlFile);
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement