Search code examples
phpxmldomsimplexml

SimpleXML inserting new line


Have this sample.xml:

<FacturacionAR>
  <Factura xsi:type="FacturaAR">
    <TipoNota>Boleta de Ventas y Servicios</TipoNota>
    <Agencia>LUIL</Agencia>
    <NroFactura>5040</NroFactura>
    <Cliente>JOHAO SMITH CART</Cliente>
    <Ciudad>NUNORK</Ciudad>
    <Direccion>CALLE VITAL DE MELLO</Direccion>
    <Barrio>JAJJKIU</Barrio>
    <Estado>Cancelada</Estado>  
  </Factura>
</FacturacionAR>

I want to add "Telefono" every time this node is missing, just after "Barrio", so I tried to do in php:

$filename = "sample.xml";

$FacturacionAR = simplexml_load_file($filename,null,true);

 function simplexml_insert_after(SimpleXMLElement $sxe, SimpleXMLElement $insert, SimpleXMLElement $target)
 {
     $target_dom = dom_import_simplexml($target);
     $target_dom->formatOutput = true;
      $target_dom->preserveWhiteSpace = false;
     $insert_dom = $target_dom->ownerDocument->importNode(dom_import_simplexml($insert), true);
     if ($target_dom->nextSibling) {
          $result = $target_dom->parentNode->insertBefore($insert_dom, $target_dom->nextSibling);
          $target_dom->parentNode->insertBefore($target_dom->ownerDocument->createTextNode("\n"), $result);
          return $result;
     } else {
          return $target_dom->parentNode->appendChild($insert_dom);
     }
 }

foreach ($FacturacionAR->Factura as $Factura) {

    if (!isset($Factura->Telefono)) {
                        $meta2 = new SimpleXMLElement("<Telefono/>");
                        $target = current($FacturacionAR->xpath('//Barrio[last()]'));
                        simplexml_insert_after($FacturacionLocalizaAR, $meta2, $target);
    }

}

The expected result is:

  <Barrio>JAJJKIU</Barrio>
  <Telefono></Telefono>

But when I run the php script, this error appears:

PHP Catchable fatal error:  Argument 3 passed to simplexml_insert_after() must be an instance of SimpleXMLElement, boolean given

Any ideas?


Solution

  • OK. Upgrading to PHP 5.5.3 solved my problem.