Add XML to a PHP file

I’m trying to have my XML file generated from a PHP plugin to display this line of

<?xml-stylesheet type="text/xsl" href="commande.xsl"?>

This is my PHP file that I’m using :

Read More
<?php

if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

/**
 * Customer/Order XML Export Suite Writer Class
 *
 * Converts customer/order data into XML
 *
 * @since 1.0
 */
class WC_Customer_Order_XML_Export_Suite_Writer extends XMLWriter {


    /** @var array order/customer IDs */
    private $ids;


    /**
     * Open XML document in memory for writing and set version/encoding
     *
     * @since  1.0
     * @param array $ids order/customer IDs to generate XML for
     * @return WC_Customer_Order_XML_Export_Suite_Writer
     */
    public function __construct( $ids ) {

        $this->ids = $ids;

        // Create XML document in memory
        $this->openMemory();

        /**
         * Toggle XML file indentation on/off
         *
         * @since 1.3.0
         * @param bool $indent
         */
        $this->setIndent( apply_filters( 'wc_customer_order_xml_export_suite_xml_indent', true ) );

        /**
         * Set the XML version declaration
         *
         * @param string $xml_version
         */
        $xml_version  = apply_filters( 'wc_customer_order_xml_export_suite_xml_version', '1.0' );

        /**
         * Set the XML encoding declaration
         *
         * @param string $xml_encoding
         */
        $xml_encoding = apply_filters( 'wc_customer_order_xml_export_suite_xml_encoding', 'UTF-8' );



        /**
         * Set the XML standalone declaration
         *
         * @param string $xml_standalone
         */
        $xml_standalone = apply_filters( 'wc_customer_order_xml_export_suite_xml_standalone', 'no' );

        // Set XML version & encoding
        $this->startDocument( $xml_version, $xml_encoding );

}

    /**
     * Build XML for customers/orders in the default format
     *
     * @since 1.0
     * @return string generated XML
     */
    public function get_orders_xml() {

        // get order data in array format for passing to array_to_xml() function
        $orders = $this->get_orders( $this->ids );


        // allow array format to be modified or changed completely
        $xml_array = apply_filters( 'wc_customer_order_xml_export_suite_order_export_format', array( 'COMMANDE' => array( 'ARTICLES' => $orders ) ), $orders );

        // get root element (first key in array)
        $keys         = array_keys( $xml_array );
        $root_element = reset( $keys );

        // generate xml starting with the root element and recursively generating child elements
        SV_WC_Helper::array_to_xml( $this, $root_element, $xml_array[ $root_element ] );

        return apply_filters( 'wc_customer_order_xml_export_suite_generated_xml', $this->output_xml(), $xml_array, $orders );
    }


    /**
     * Deprecated get_orders_xml()
     *
     * @since 1.0
     * @param array $order_ids
     * @deprecated 1.1
     * @return string generated XML
     */
    public function get_order_export_xml( $order_ids ) {

        _deprecated_function( __METHOD__, '1.1', 'WC_Customer_Order_XML_Export_Suite_Writer::get_orders_xml' );
        $this->ids = $order_ids;
        return $this->get_orders_xml();
    }


    /**
     * End the XML document and output the XML stream
     *
     * @since 1.0
     * @return string generated XML
     */
    private function output_xml() {
        $this->endDocument();

        return $this->outputMemory();
    }


    /**
     * Add a complete attribute to element
     *
     * @since 1.0
     * @param string $id attribute key
     * @param string $value attribute value
     */
    private function addAttribute( $id, $value ) {
        $this->startAttribute( $id );
        $this->text( $value );
        $this->endAttribute();
    }


    /**
     * Creates array of given orders in standard format
     *
     * Filter in get_order_export_xml() allow modification of parent array
     * Filter in method allows modification of individual order array format
     *
     * @since 1.0
     * @param array $order_ids order IDs to generate array from
     * @return array orders in array format required by array_to_xml()
     */
    private function get_orders( $order_ids ) {

        $order_data = array();

        // loop through each order
        foreach ( $order_ids as $order_id ) {

            // instantiate WC_Order object
            $order = SV_WC_Plugin_Compatibility::wc_get_order( $order_id );

            $shipping_methods = $shipping_methods_ids = array();

            foreach ( $order->get_shipping_methods() as $method ) {

                $shipping_methods[]   = $method['name'];
                $shipping_methods_ids[] = $method['method_id'];
            }

            // get fee items & total
            $fee_total = 0;
            foreach ( $order->get_fees() as $fee_id => $fee ) {
                $fee_total += $fee['line_total'];
            }

            // Standard format
            $order_data[] = apply_filters( 'wc_customer_order_xml_export_suite_order_export_order_list_format', array(
                'VERSION'  => 'V.2.0.F',
                'NO_COMMANDE'            => $order->id,
                'OrderNumber'        => $order->get_order_number(),
                'DATE_COMMANDE'          => $order->order_date,
                'OrderStatus'        => SV_WC_Plugin_Compatibility::get_order_status( $order ),
                'BIllafds'   => $order->billing_first_name,
                'BillingLastName'    => $order->billing_last_name,
                'NOM_CLIENT'    => $order->billing_first_name . ' ' . $order->billing_last_name,
                'NO_SUCCURSALE'     => ' ',
                'NOM_SUCCURSALE'     => ' ',
                'NO_CLIENT_CLIENT'     => ' ',
                'NO_SUCCURSALE_CLIENT'     => ' ',
                'REGROUPEMENT_FACTURE'     => 'O',
                'NOM_DE_LA_CIE'     => $order->billing_company,
                'ADRESSE_1'    => $order->billing_address_1,
                'ADRESSE_2'    => $order->billing_address_2,
                'VILLE'        => $order->billing_city,
                'PROVINCE'       => $order->billing_state,
                'CODE_POSTAL'    => $order->billing_postcode,
                'PAYS'     => $order->billing_country,
                'TELEPHONE'       => $order->billing_phone,
                'COURRIEL'       => $order->billing_email,
                'ShippingFirstName'  => $order->shipping_first_name,
                'ShippingLastName'   => $order->shipping_last_name,
                'ShippingFullName'   => $order->shipping_first_name . ' ' . $order->shipping_last_name,
                'NOM_DE_LA_CIE'    => $order->shipping_company,
                'ADRESSE_1'   => $order->shipping_address_1,
                'ADRESSE_2'   => $order->shipping_address_2,
                'VILLE'       => $order->shipping_city,
                'PROVINCE'      => $order->shipping_state,
                'CODE_POSTAL'   => $order->shipping_postcode,
                'PAYS'    => $order->shipping_country,
                'ShippingMethodId'   => implode( ',', $shipping_methods_ids ),
                'MODE_LIVRAISON'     => implode( ', ', $shipping_methods ),
                'PaymentMethodId'    => $order->payment_method,
                'PaymentMethod'      => $order->payment_method_title,
                'OrderDiscountTotal' => SV_WC_Plugin_Compatibility::is_wc_version_gte_2_3() ? $order->get_total_discount() : $order->get_order_discount(),
                'CartDiscountTotal'  => SV_WC_Plugin_Compatibility::is_wc_version_gte_2_3() ? $order->get_total_discount() : $order->get_cart_discount(),
                'DiscountTotal'      => $order->get_total_discount(),
                'ShippingTotal'      => $order->get_total_shipping(),
                'ShippingTaxTotal'   => $order->get_shipping_tax(),
                'OrderTotal'         => $order->get_total(),
                'FeeTotal'           => $fee_total,
                'TaxTotal'           => $order->get_total_tax(),
                'CompletedDate'      => $order->completed_date,
                'CustomerNote'       => $order->customer_note,
                'NO_CLIENT'         => SV_WC_Plugin_Compatibility::get_order_user_id( $order ),
                'ARTICLE'     => $this->get_line_items( $order )

            ), $order );

        }

        return $order_data;
    }


    /**
     * Creates array of order line items in format required for xml_to_array()
     *
     * Filter in method allows modification of individual line items array format
     *
     * @since 1.0
     * @param object $order
     * @return array - line items in array format required by array_to_xml()
     */
    private function get_line_items( $order ) {

        $items = array();

        // loop through each item in order
        foreach ( $order->get_items() as $item_id => $item ) {

            $item['id'] = $item_id;

            // discard taxes and fees
            if ( isset( $item['type'] ) && 'line_item' !== $item['type'] ) {
                continue;
            }

            // get the product
            $product = $order->get_product_from_item( $item );

            // instantiate line item meta
            $item_meta = new WC_Order_Item_Meta( $item['item_meta'] );
            $item_meta = $item_meta->display( true, true );

            // remove HTML
            $item_meta = preg_replace( '/<[^>]*>/', ' ', $item_meta );

            // remove control characters
            $item_meta = str_replace( array( "r", "n", "t" ), '', $item_meta );

            // really remove all HTML
            $item_meta = strip_tags( $item_meta );

            $item_format = array();

            $item_format['SKU']       = $product ? $product->get_sku() : '';  // handling for permanently deleted product
            $item_format['ItemName']  = html_entity_decode( $product ? $product->get_title() : $item['name'], ENT_NOQUOTES, 'UTF-8' );
            $item_format['Quantiti']  = $item['qty'];
            $item_format['Price']     = $order->get_item_total( $item );
            $item_format['LineTotal'] = $item['line_total'];

            if ( 'yes' === get_option( 'woocommerce_calc_taxes' ) && 'yes' === get_option( 'woocommerce_prices_include_tax' ) ) {
                $item_format['PriceInclTax']     = $order->get_item_total( $item, true );
                $item_format['LineTotalInclTax'] = $item['line_total'] + $item['line_tax'];
            }



            // build array
            $items[] = apply_filters( 'wc_customer_order_xml_export_suite_order_export_line_item_format', $item_format, $order, $item );
        }

        return $items;
    }

/****************************************************************************/

    /**
     * Get the XML for customers
     *
     * @since 1.1
     * @return string XML data
     */
    public function get_customers_xml() {

        $customers = array();

        // get customers to export
        foreach ( $this->ids as $order_id ) {

            $billing_email = get_post_meta( $order_id, '_billing_email', true );

            // skip orders without a billing email
            if ( ! $billing_email ) {
                continue;
            }

            $customers[ $order_id ] = $billing_email;
        }

        // ensure each customer has a unique billing email
        $customers = array_unique( $customers );

        // get order data in array format for passing to array_to_xml() function
        $customers = $this->get_customers( $customers );

        // allow array format to be modified or changed completely
        $xml_array = apply_filters( 'wc_customer_order_xml_export_suite_customer_export_format', array( 'Customers' => array( 'Customer' => $customers) ), $customers );

        // get root element (first key in array)
        $keys         = array_keys( $xml_array );
        $root_element = reset( $keys );

        // generate xml starting with the root element and recursively generating child elements
        SV_WC_Helper::array_to_xml( $this, $root_element, $xml_array[ $root_element ] );

        return apply_filters( 'wc_customer_order_xml_export_suite_generated_xml', $this->output_xml(), $xml_array, $customers );
    }


    /**
     * Get the customer data
     *
     * @since 1.1
     * @param array $customers
     * @return array customer data in the format key => content
     */
    private function get_customers( $customers ) {

        $customer_data = array();

        foreach ( $customers as $order_id => $customer_email ) {

            $user = get_user_by( 'email', $customer_email );

            // guest, get info from order
            if ( ! $user ) {

                $order = SV_WC_Plugin_Compatibility::wc_get_order( $order_id );

                // create blank user
                $user = new stdClass();

                // set properties on user
                $user->ID                  = 0;
                $user->first_name          = $order->billing_first_name;
                $user->last_name           = $order->billing_last_name;
                $user->user_email          = $order->billing_email;
                $user->user_registered     = $order->order_date;
                $user->billing_first_name  = $order->billing_first_name;
                $user->billing_last_name   = $order->billing_last_name;
                $user->billing_company     = $order->billing_company;
                $user->billing_email       = $order->billing_email;
                $user->billing_phone       = $order->billing_phone;
                $user->billing_address_1   = $order->billing_address_1;
                $user->billing_address_2   = $order->billing_address_2;
                $user->billing_postcode    = $order->billing_postcode;
                $user->billing_city        = $order->billing_city;
                $user->billing_state       = $order->billing_state;
                $user->billing_country     = $order->billing_country;
                $user->shipping_first_name = $order->shipping_first_name;
                $user->shipping_last_name  = $order->shipping_last_name;
                $user->shipping_company    = $order->shipping_company;
                $user->shipping_address_1  = $order->shipping_address_1;
                $user->shipping_address_2  = $order->shipping_address_2;
                $user->shipping_postcode   = $order->shipping_postcode;
                $user->shipping_city       = $order->shipping_city;
                $user->shipping_state      = $order->shipping_state;
                $user->shipping_country    = $order->shipping_country;
            }

            /**
             * XML Export Customer Data
             *
             * Filter the individual customer data
             *
             * @since 1.1
             * @param array $customer_data
             * @param WP_User $user WP User object
             * @param int $order_id an order ID for the customer
             * @param WC_Customer_Order_XML_Export_Suite_Writer $this, writer instance
             */
            $customer_data[] = apply_filters( 'wc_customer_order_xml_export_suite_customer_export_data', array(
                'CustomerID'        => $user->ID,
                'FirstName'         => $user->first_name,
                'LastName'          => $user->last_name,
                'Email'             => $user->user_email,
                'DateRegistered'    => $user->user_registered,
                'BillingFirstName'  => $user->billing_first_name,
                'BillingLastName'   => $user->billing_last_name,
                'BillingCompany'    => $user->billing_company,
                'BillingEmail'      => $user->billing_email,
                'BillingPhone'      => $user->billing_phone,
                'Billingaddress1'   => $user->billing_address_1,
                'Billingaddress2'   => $user->billing_address_2,
                'Billingpostcode'   => $user->billing_postcode,
                'Billingcity'       => $user->billing_city,
                'Billingstate'      => $user->billing_state,
                'Billingcountry'    => $user->billing_country,
                'ShippingFirstName' => $user->shipping_first_name,
                'ShippingLastName'  => $user->shipping_last_name,
                'ShippingCompany'   => $user->shipping_company,
                'ShippingAddress1'  => $user->shipping_address_1,
                'ShippingAddress2'  => $user->shipping_address_2,
                'ShippingPostcode'  => $user->shipping_postcode,
                'ShippingCity'      => $user->shipping_city,
                'ShippingState'     => $user->shipping_state,
                'ShippingCountry'   => $user->shipping_country,
            ), $user, $order_id, $this );
        }

        return $customer_data;
    }


} //end WC_Customer_Order_XML_Export_Suite_Writer class

So far this displays properly this line :

<?xml version="1.0" encoding="utf-8"?>

But I’d like to have the one mentionned above as well right under it. I can’t seem to find any ways to do this.

This is where it’s being instantiated :

class WC_Customer_Order_XML_Export_Suite_Handler {


    /** @var array order/customer IDs to export */
    public $ids;

    /** @var string file name for export or download */
    public $filename;

    /** @var WC_Customer_Order_XML_Export_Suite_Writer */
    private $writer;


    /**
     * Initializes the export object from an array of valid order/customer IDs and sets the filename
     *
     * @since 1.0
     * @param int|array $ids order/customer IDs to export
     * @param string $export_type what is being exported, `orders` or `customers`
     * @return WC_Customer_Order_XML_Export_Suite_Handler
     */
    public function __construct( $ids, $export_type = 'orders' ) {

        // handle single order/customer exports
        if ( ! is_array( $ids ) ) {

            $ids = array( $ids );
        }

        $this->export_type = $export_type;
        $this->ids = $ids;

        // set file name
        $this->filename = $this->replace_filename_variables();

        // instantiate writer here
        $this->writer = new WC_Customer_Order_XML_Export_Suite_Writer( $this->ids );
    }


    /**
     * Exports orders/customers to XML and downloads via browser
     *
     * @since 1.1
     */
    public function download() {

        $this->export_via( 'download' );
    }


    /**
     * Exports test XML and downloads via browser
     *
     * @since 1.1
     */
    public function test_download() {

        $this->test_export_via( 'download' );
    }


    /**
     * Exports orders/customers to XML and uploads to remote server
     *
     * @since 1.1
     */
    public function upload() {

        $this->export_via( 'ftp' );
    }


    /**
     * Exports test XML and uploads to remote server
     *
     * @since 1.1
     */
    public function test_upload() {

        $this->test_export_via( 'ftp' );
    }


    /**
     * Exports orders/customers to XML and HTTP POSTs to remote server
     *
     * @since 1.1
     */
    public function http_post() {

        $this->export_via( 'http_post' );
    }


    /**
     * Exports test XML and HTTP POSTs to remote server
     *
     * @since 1.1
     */
    public function test_http_post() {

        $this->test_export_via( 'http_post' );
    }


    /**
     * Exports orders/customers to XML and emails admin with XML as attachment
     *
     * @since 1.1
     */
    public function email() {

        $this->export_via( 'email' );
    }


    /**
     * Exports test XML and emails admin with XML as attachment
     *
     * @since 1.1
     */
    public function test_email() {

        $this->test_export_via( 'email' );
    }


    /**
     * Exports XML via the given method
     *
     * @since 1.1
     * @param string $method the export method, `download`, `ftp`, `http_post`, `email`
     */
    public function export_via( $method ) {

        // try to set unlimited script timeout
        @set_time_limit( 0 );

        try {

            // get method (download, FTP, etc)
            $export = $this->get_export_method( $method );

            if ( ! is_object( $export ) ) {

                throw new Exception( sprintf( __( 'Invalid Export Method: %s', WC_Customer_Order_XML_Export_Suite::TEXT_DOMAIN ), $method ) );
            }

            if ( 'orders' == $this->export_type ) {

                // mark each order as exported
                // this must be done before download, as the download function exits() to prevent additional output from contaminating the XML file
                $this->mark_orders_as_exported( $method );
            }

            $export->perform_action( $this->filename, 'orders' == $this->export_type ? $this->writer->get_orders_xml() : $this->writer->get_customers_xml() );

        } catch ( Exception $e ) {

            // log errors
            wc_customer_order_xml_export_suite()->log( $e->getMessage() );
        }
    }


    /**
     * Exports a test XML file via the given method
     *
     * @since 1.1
     * @param string $method the export method
     * @return string 'Success' or error message
     */
    public function test_export_via( $method ) {

        // try to set unlimited script timeout
        @set_time_limit( 0 );

        try {

            // get method (download, FTP, etc)
            $export = $this->get_export_method( $method );

            if ( ! is_object( $export ) ) {

                throw new Exception( sprintf( __( 'Invalid Export Method: %s', WC_Customer_Order_XML_Export_Suite::TEXT_DOMAIN ), $method ) );
            }

            // simple test XML
            $export->perform_action( 'test.xml', '<?xml version="1.0"?><test></test>' );

            return __( 'Test was successful!', WC_Customer_Order_XML_Export_Suite::TEXT_DOMAIN );

        } catch ( Exception $e ) {

            // log errors
            wc_customer_order_xml_export_suite()->log( $e->getMessage() );

            return sprintf( __( 'Test failed: %s', WC_Customer_Order_XML_Export_Suite::TEXT_DOMAIN ), $e->getMessage() );
        }
    }


    /**
     * Returns the export method object
     *
     * @since 1.1
     * @param string $method the export method, `download`, `ftp`, `http_post`, or `email`
     * @return object the export method
     */
    private function get_export_method( $method ) {

        // get the export method specified
        switch ( $method ) {

            case 'download':
                require_once( wc_customer_order_xml_export_suite()->get_plugin_path() . '/includes/export-methods/class-wc-customer-order-xml-export-suite-method-download.php' );
                return new WC_Customer_Order_XML_Export_Suite_Method_Download();

            case 'ftp':
                // abstract FTP class
                require_once( wc_customer_order_xml_export_suite()->get_plugin_path() . '/includes/export-methods/ftp/abstract-wc-customer-order-xml-export-suite-method-file-transfer.php' );

                $security = get_option( 'wc_customer_order_xml_export_suite_ftp_security' );

                switch ( $security ) {

                    // FTP over SSH
                    case 'sftp' :
                        require_once( wc_customer_order_xml_export_suite()->get_plugin_path() . '/includes/export-methods/ftp/class-wc-customer-order-xml-export-suite-method-sftp.php' );
                        return new WC_Customer_Order_XML_Export_Suite_Method_SFTP();

                    // FTP with Implicit SSL
                    case 'ftp_ssl' :
                        require_once( wc_customer_order_xml_export_suite()->get_plugin_path() . '/includes/export-methods/ftp/class-wc-customer-order-xml-export-suite-method-ftp-implicit-ssl.php' );
                        return new WC_Customer_Order_XML_Export_Suite_Method_FTP_Implicit_SSL();

                    // FTP with explicit SSL/TLS *or* regular FTP
                    case 'ftps' :
                    case 'none' :
                        require_once( wc_customer_order_xml_export_suite()->get_plugin_path() . '/includes/export-methods/ftp/class-wc-customer-order-xml-export-suite-method-ftp.php' );
                        return new WC_Customer_Order_XML_Export_Suite_Method_FTP();
                }
                break;

            case 'http_post':
                require_once( wc_customer_order_xml_export_suite()->get_plugin_path() . '/includes/export-methods/class-wc-customer-order-xml-export-suite-method-http-post.php' );
                return new WC_Customer_Order_XML_Export_Suite_Method_HTTP_POST();

            case 'email':
                require_once( wc_customer_order_xml_export_suite()->get_plugin_path() . '/includes/export-methods/class-wc-customer-order-xml-export-suite-method-email.php' );
                return new WC_Customer_Order_XML_Export_Suite_Method_Email();

            default:
                return null;
        }
    }


    /**
     * Marks orders as exported by setting the `_wc_customer_order_xml_export_suite_is_exported` order meta flag
     *
     * @since 1.1
     * @param string $method the export method, `download`, `ftp`, `http_post`, or `email`
     */
    public function mark_orders_as_exported( $method = 'download' ) {

        foreach ( $this->ids as $order_id ) {

            // add exported flag
            update_post_meta( $order_id, '_wc_customer_order_xml_export_suite_is_exported', 1 );

            $order = SV_WC_Plugin_Compatibility::wc_get_order( $order_id );

            switch ( $method ) {

                // note that order downloads using the AJAX order action are not marked or noted, only bulk order downloads
                case 'download':
                    $message = __( 'downloaded.', WC_Customer_Order_XML_Export_Suite::TEXT_DOMAIN );
                    break;

                case 'ftp':
                    $message = __( 'uploaded to remote server.', WC_Customer_Order_XML_Export_Suite::TEXT_DOMAIN );
                    break;

                case 'http_post':
                    $message = __( 'POSTed to remote server.', WC_Customer_Order_XML_Export_Suite::TEXT_DOMAIN );
                    break;

                case 'email':
                    $message = __( 'emailed.', WC_Customer_Order_XML_Export_Suite::TEXT_DOMAIN );
                    break;
            }

            $order->add_order_note( sprintf( __( 'Order exported to XML and successfully %s', WC_Customer_Order_XML_Export_Suite::TEXT_DOMAIN ), $message ) );
        }
    }


    /**
     * Replaces variables in file name setting (e.g. %%timestamp%% becomes 2013_03_20_16_22_14 )
     *
     * @since 1.0
     * @return string filename with variables replaced
     */
    private function replace_filename_variables() {

        $pre_replace_filename = get_option( 'orders' == $this->export_type ? 'wc_customer_order_xml_export_suite_orders_filename' : 'wc_customer_order_xml_export_suite_customers_filename' );

        $variables   = array( '%%timestamp%%', '%%order_ids%%' );
        $replacement = array( date( 'Y_m_d_H_i_s' ), implode( '-', $this->ids ) );

        $post_replace_filename = str_replace( $variables, $replacement, $pre_replace_filename );

        return apply_filters( 'wc_customer_order_xml_export_suite_export_file_name', $post_replace_filename, $pre_replace_filename, $this->ids );
    }


} //end WC_Customer_Order_XML_Export_Suite_Handler class

Thank you!

Related posts