/ php

Generate XML files using PHP

XML files are a popular data interchange and storage format on the net.
This method example explores how to generate XML files using php.
Aditional features were added, like check for a folder where it will save the generated XML and at the end just returns the XML file path.

function GenerateXml()
    {
        $requestXml = new DOMDocument("1.0", 'UTF-8');
        $requestXml->formatOutput = true;

        $requestString = $requestXml->createElement("PAYMENT");
        $requestXml->appendChild($requestString);

        $node = $requestXml->createElement("ORDERID");
        $node->appendChild($requestXml->createTextNode($this->orderId));
        $requestString->appendChild($node);

        $node = $requestXml->createElement("AMOUNT");
        $requestString->appendChild($node);
        $nodeText = $requestXml->createTextNode($this->amount);
        $node->appendChild($nodeText);

        $node = $requestXml->createElement("DATETIME");
        $requestString->appendChild($node);
        $nodeText = $requestXml->createTextNode($this->dateTime);
        $node->appendChild($nodeText);

        $node = $requestXml->createElement("CARDNUMBER");
        $requestString->appendChild($node);
        $nodeText = $requestXml->createTextNode($this->cardNumber);
        $node->appendChild($nodeText);

        $node = $requestXml->createElement("CARDTYPE");
        $requestString->appendChild($node);
        $nodeText = $requestXml->createTextNode($this->cardType);
        $node->appendChild($nodeText);

        $node = $requestXml->createElement("CARDEXPIRY");
        $requestString->appendChild($node);
        $nodeText = $requestXml->createTextNode($this->cardExpiry);
        $node->appendChild($nodeText);

        $node = $requestXml->createElement("CARDHOLDERNAME");
        $requestString->appendChild($node);
        $nodeText = $requestXml->createTextNode($this->cardHolderName);
        $node->appendChild($nodeText);

        $node = $requestXml->createElement("HASH");
        $requestString->appendChild($node);
        $nodeText = $requestXml->createTextNode($this->hash);
        $node->appendChild($nodeText);

        $node = $requestXml->createElement("CURRENCY");
        $requestString->appendChild($node);
        $nodeText = $requestXml->createTextNode($this->currency);
        $node->appendChild($nodeText);

        $node = $requestXml->createElement("EMAIL");
        $requestString->appendChild($node);
        $nodeText = $requestXml->createTextNode($this->email);
        $node->appendChild($nodeText);

        $requestXml->saveXML();
            
        // Check if folder exist
        if (!is_dir(VAR_DIR)) {
            mkdir(VAR_DIR);
        }
        
        $xml_full_local_path = VAR_DIR.'/output.xml';
        $requestXml->save($xml_full_local_path);
        
        return $xml_full_local_path;
    }
}
Generate XML files using PHP
Share this

Subscribe to NL Slack