1

I am reading a XML file that has the following content:

<column name="title">
<![CDATA[
Sets inktcartridges geschikt voor Brother, Canon, Epson of HP printers (vanaf € 19,95)
]]>
</column>
<column name="description">
<![CDATA[
Niets zo storend als een printer zonder inkt als je net je 300 pagina’s tellende scriptie moet inleveren. Voorkom dit soort narigheden met cartridges voor verschillende printers in zwart en in kleur.
]]>
</column>

Every item will get an empty index when I parse the data with simplexml_load_string:

$xml = simplexml_load_string($data,'SimpleXMLElement',LIBXML_NOCDATA);  

output:

[1] => Sets inktcartridges geschikt voor Brother, Canon, Epson of HP printers (vanaf € 19,95)
        [2] => Niets zo storend als een printer zonder inkt als je net je 300 pagina’s tellende scriptie moet inleveren. Voorkom dit soort narigheden met cartridges voor verschillende printers in zwart en in kleur.

How can I tell simplexml_load_string that the name item in the column needs to be the index?

1 Answers1

0

I think you cannot do that in a single go.. You could do like this..

<?php
$string = <<<XML
<?xml version='1.0'?>
<cols>
<column name="title">
<![CDATA[
Sets inktcartridges geschikt voor Brother, Canon, Epson of HP printers (vanaf € 19,95)
]]>
</column>
<column name="description">
<![CDATA[
Niets zo storend als een printer zonder inkt als je net je 300 pagina’s tellende scriptie moet inleveren. Voorkom dit soort narigheden met cartridges voor verschillende printers in zwart en in kleur.
]]>
</column>
</cols>
XML;
echo "<pre>";
$xml = simplexml_load_string($string,'SimpleXMLElement',LIBXML_NOCDATA);
$new_arr = array();
for($i=0;$i<count($xml->column);$i++)
{
    $new_arr[(string)$xml->column[$i]->attributes()[0]]=trim(strip_tags($xml->column[$i]->saveXML()));
}
print_r($new_arr);

OUTPUT :

Array
(
    [title] => Sets inktcartridges geschikt voor Brother, Canon, Epson of HP printers (vanaf € 19,95)
    [description] => Niets zo storend als een printer zonder inkt als je net je 300 pagina’s tellende scriptie moet inleveren. Voorkom dit soort narigheden met cartridges voor verschillende printers in zwart en in kleur.
)

Working Demo

Shankar Narayana Damodaran
  • 68,075
  • 43
  • 96
  • 126
  • Check the page source, the data will start with: " – user3544172 Apr 17 '14 at 08:36
  • The output that you gave in plaintext is what I need. The name of the column needs to be the index and the content of the column the value. That is without the XML of the column itself. – user3544172 Apr 17 '14 at 09:13