0

I have a XML file, where some elements will be empty. The issue is, that this code, creates an empty array, if the element is empty. Som for the XML example below, the result from JSON_DECODE would be:

I have tried setting depth to two, with no luck.

[26272] => Array (
    [productname] => Some product name
    [ean] => Array ( )
)

Example XML:

<item>
    <productname>Some product name</productname>
    <ean></ean>
</item>

The code i´m using:

$xml = simplexml_load_file($url);
$json = json_encode($xml,JSON_PRETTY_PRINT);
$products = json_decode($json, TRUE);
8
  • This is a fundamental limitation of the XML format. It can't distinguish between empty lists and empty strings. Simple XML assumes that <ean></an> is an empty list.
    – Barmar
    Commented Aug 11, 2022 at 21:12
  • Thanks @Barmar. Ofcourse I can check if every element is an array, and work from there, but the real life XML has a lot more elements. Is there a possible workaround? Commented Aug 11, 2022 at 21:16
  • I looked at all the flags available to simplexml_load_file(), I don't see any that will make it load <ean></ean> as a string node rather than an element.
    – Barmar
    Commented Aug 11, 2022 at 21:28
  • Can you just remove empty nodes from the XML?
    – Chris Haas
    Commented Aug 11, 2022 at 21:30
  • @ChrisHaas Haven´t thought about Xpath, that could actually be a solution. I will look in to it. Barmar Thanks for the try - I hope to find a good solution. Commented Aug 11, 2022 at 21:36

1 Answer 1

0

Just for info, if someone else can use it. I figured it out, by this post, and used this function, to run through and replace the empty arrays:

function replaceArrayToString($arr) {
   $newArr = array();
   foreach($arr as $key=>$value)
   {
       if (is_array($value))
       {
          unset($arr[$key]);

           //Is it an empty array, make it a string
           if (empty($value)) {
               $newArr[$key] = '';
           }
           else {
               $newArr[$key] = replaceArrayToString($value);
           }

       }
       else {
           $newArr[$key] = $value; 
       }

   }
   return $newArr;

}

Not the answer you're looking for? Browse other questions tagged or ask your own question.