0

I am trying to retreive a string in a XML file using simplexml. But the string contains the character "&". So I think I have to use CDATA to get the value. I am really new to this and don't no how to do it. this is just an example of what I want.

Example.php

<?php
  $xmlstr = <<<XML
  <?xml version='1.0' standalone='yes'?>
  <Books>
     <Book>
        <title> PHP & XML </title>
        <author> Some text </author>
        <price> Some text </price>
     </Book>
     <Book>
        <title> Java & Coding </title>
        <author> Some text </author>
        <price> Some text </price>
     </Book>

  </Books>
  XML;
?>

And this is my calling php file

call.php

<?php
  include 'Example.php';

  $xml = simplexml_load_string($xmlstr);
  $abc = $xml->Book[0]->title[0];
  echo $abc;
?>

And it is giving an error because of the character "&". I cannot change my XML. Any modification can be done to call.php Any help regarding the matter would be highly appreciate. Thanx.

gecco
  • 281
  • 4
  • 18
  • Well, the XML is technically invalid. You *should* and *need* to change it. – deceze May 14 '13 at 05:42
  • I'm sorry. Can you tell me which part of my XML is invalid? – gecco May 14 '13 at 05:46
  • The `&`. No bare `&` is allowed in bare text nodes, it is *required* to be `&`. – deceze May 14 '13 at 06:01
  • Yes that is my problem. I cannot change it. So when I retrieve the string inside tag, I have to come up with a way. Do you have any idea how to do that. I cannot change my Example.php as it is not accessible to me. I only can do changes to call.php – gecco May 14 '13 at 06:05
  • Thank you for your help. I sort it out with the help from @NullVoid :) – gecco May 14 '13 at 06:25

1 Answers1

0

You have an exact question like this SO PHP, SimpleXML, decoding entities in CDATA

It has explain about CDATA which can be used in case of

special characters (in particular, >, < and &) to be escaped. A CDATA section containing the character & is the same as a normal text node containing &.

Have a look on this.

Edit

Here is one solution if you load every time your example.php code into string then below is one solution.

  $xmlstr = str_replace("&","&amp;",$xmlstr);
  $xml = simplexml_load_string($xmlstr);
  $abc = $xml->Book[0]->title[0];
  echo $abc;
Community
  • 1
  • 1
Smile
  • 2,770
  • 4
  • 35
  • 57
  • Yes I know how to use CDATA inside a XML PHP <![CDATA[ & ]]> XML But my problem is how can I use it in my call.php as I cannot do any changes to my Example.php – gecco May 14 '13 at 05:54