G
G
Gennady2020-02-17 19:49:27
PHP
Gennady, 2020-02-17 19:49:27

How to insert a tag in XML (simplexml)?

You need to insert a new tag with a static value in the XML:

<?xml version="1.0" encoding="windows-1251"?>
<!DOCTYPE yml_catalog SYSTEM "shops.dtd">
<yml_catalog date="2020-02-17 16:45">
    <shop>
        <offers>
            <offer id="2164" available="true" >
                <url>https://</url>
                <price>779</price>
                <currencyId>RUR</currencyId>
            </offer>
            <offer id="2165" available="true" >
                <url>https://2</url>
                <price>780</price>
                <currencyId>RUR</currencyId>
            </offer>
        </offers>
    </shop>
</yml_catalog>

You need to add a static one:

<delivery-options>
<option cost="300" days="4" order-before="18"/>
</delivery-options>

I do

$xml = simplexml_load_file('https://URI');
foreach ($xml->shop->offers->offer as $offer) {
    $name = $offer->name;
    $details = $offer->addChild('delivery-options');
}

The tag is added as: <delivery-options/>

I do not understand why it is not a paired tag, and how to add it <option cost="300" days="4" order-before="18"/>

. Is it possible to somehow insert a simple line? Or somehow else?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
Gennady, 2020-02-17
@theblackpost

In general, like this

foreach ($xml->shop->offers->offer as $offer) {
        $name = $offer->name;
        $details = $offer->addChild('delivery-options',' ');
        $details_option = $details->addChild('option');
        $details_option->addAttribute('cost', '300');
        $details_option->addAttribute('days', '4');
    }


echo $xml->asXML();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question