I need to create an endpoint that when called returns an XML with the products of the store. I have the XML generated, but I don’t know how to make the endpoint return it in XML format, because now it returns it in JSON format, and being an XML, it does not return it well.
This is my code:
<?php
/**
* Plugin Name: example
* Plugin URI: https://www.example.es/
* Description: example
* Version: 1.0
* Author: example
* Author URI: https://www.example.es/
*/
function smg_feed() {
$args = array( 'post_status' => 'publish', numberposts => -1 );
$products = wc_get_products($args);
$xml_header="<?xml version="1.0" encoding="UTF-8"?><Document></Document>";
$xml = new SimpleXMLElement($xml_header);
foreach($products as $product) {
$data = $product->get_data();
$sku = $data['sku'];
$categoriasNombres = array();
$subcategoriasNombres = array();
foreach( wp_get_post_terms( $data['id'], 'product_cat' ) as $term ){
if( $term ){
if ($term->name == 'XXXX' || $term->name == 'YYYY') {
array_push($categoriasNombres, $term->name);
} else {
array_push($subcategoriasNombres, $term->name);
}
}
}
$categoriasNombres = implode(',', $categoriasNombres);
$subcategoriasNombres = implode(',', $subcategoriasNombres);
$propiedadesNombres = array();
foreach( wp_get_post_terms( $data['id'], 'product_tag' ) as $term ){
if( $term ){
array_push($propiedadesNombres, $term->name);
}
}
$propiedadesNombres = implode(',', $propiedadesNombres);
$nombre = $data['name'];
$formatosNombres = array();
foreach( wp_get_post_terms( $data['id'], 'pa_formato' ) as $term ){
if( $term ){
array_push($formatosNombres, $term->name);
}
}
$formatosNombres = implode(',', $formatosNombres);
$metaData = $data['meta_data'];
foreach($metaData as $item) {
if ($item->key == '_role_based_price') {
$obj = $item->value;
$precio = $obj['api1']['regular_price'];
$precioEspecial = $obj['api2']['regular_price'];
}
}
$row = $xml->addChild('row');
$row->addChild('sku', $sku);
$row->addChild('categorias', $categoriasNombres);
$row->addChild('subcategorias', $subcategoriasNombres);
$row->addChild('propiedades', $propiedadesNombres);
$row->addChild('nombre', $nombre);
// $row->addChild('imagen', );
$row->addChild('formatos', $formatosNombres);
$row->addChild('precio', $data['regular_price']);
$row->addChild('precio_especial', $precioEspecial);
}
$output = $xml->asXML();
return $output;
}
add_action('rest_api_init', function() {
register_rest_route('smg/v1', 'feed', [
'methods' => 'GET',
'callback' => 'smg_feed',
]);
});
But when I make the call to the endpoint what it returns is this:
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n
<Document>
<row>
<sku\/>
<categorias>Nutrici\u00f3n<\/categorias>
<subcategorias>Nutridefense Plus<\/subcategorias>
<propiedades>todo<\/propiedades>
<nombre>NutriDefense plus<\/nombre>
<formatos\/>
<precio>29,90<\/precio>
<precio_especial>26,52<\/precio_especial>
<\/row>
<\/Document>\n"
How can I make it return it in XML format? Thank you very much.
Regards.