1

My XML looks like this:

<?xml version="1.0" encoding="utf-8"?>
<SHOP>
  <SHOPITEM>
    <ITEM_ID>8</ITEM_ID>
    <PRODUCT>Body EMMER W 12</PRODUCT>
    <DESCRIPTION>
      <p>Test 1
        <br />Good
        <br />Big
        <br />Long
        <br />Works
      </p>
    </DESCRIPTION>
  </SHOPITEM>
</SHOP>

SEE: node DESCRIPTION contains HTML content, these are not another nodes.

Then in PHP I open XML file:

$xml = simplexml_load_file("file1.xml");
foreach($xml->children() as $data) {
  ...
}

Then I want to save some values, so:

$product = array(
  "id" => (string) $data->ITEM_ID,
  "item_name" => (string) $data->PRODUCT,
  "description" => (string) $data->DESCRIPTION
);

But when I print these to the HTML table, description is empty. Reason is, that PHP recognize that <p> element like another node, so there will be no text/value. What should I do?

2
  • Into XML description should be save with function 'htmlspecialchars' Commented Oct 24, 2015 at 17:52
  • I can't edit XMLs and I'm not the one who creates these files. I just have to process them. @anttiviljami found the solution. Commented Oct 24, 2015 at 17:54

1 Answer 1

1

Looks like your XML file is actually a mix of HTML and XML, which is a bit messy. The best thing to do here would be to fix this by wrapping the HTML in <![CDATA[""]]> (character data) tags which would enable you to use exactly the PHP script you're trying to use.

So instead of

<DESCRIPTION>
  <p>Test 1
    <br />Good
    <br />Big
    <br />Long
    <br />Works
  </p>
</DESCRIPTION>

You should use

<DESCRIPTION>
  <![CDATA[
    <p>Test 1
      <br />Good
      <br />Big
      <br />Long
      <br />Works
    </p>
  ]]>
</DESCRIPTION>

If editing the xml file isn't an option, you can just to stringify the children with SimpleXMLElement::asXML() like this:

$product = array(
  //...
  "description" => (string) $data->DESCRIPTION->asXML(),
);

EDIT:

Please note that using the latter method, $data->DESCRIPTION->asXML() will include the wrapping <DESCRIPTION> tabs.

Sign up to request clarification or add additional context in comments.

1 Comment

You are great! I forgot to say, that I can't edit XMLs, but you answered also to that problem. Thanks a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.