0

I'm working on xml.php file structured below:

<?php
    $xmlstr = <<<'XML'
    <?xml version='1.0' standalone='yes'?>

<root>
  <subroot>
    <![CDATA[

... some php code here ...

            ]]>
  </subroot>
</root>

    XML;
    ?>

I want to add the below php code between CDATA so that we can call it later through index.html file:

        <?php 
          include $_SERVER['DOCUMENT_ROOT'].'xml.php';  
          $template = new SimpleXMLElement($xmlstr); 
          echo $articles->article[0]->name; 
        ?>

However, it doesn't work like this and have run out of ideas on how can we make it to work. Any suggestions?

2
  • 2
    that's not a valid xml, you need <?xml version='1.0' standalone='yes'?><root><![CDATA]]></root> Commented Oct 1, 2016 at 6:48
  • I think that your observation is correct and I have just include cdata between subroot element which is part of the root element. And according to akrys suggestion I change the last line of the code from XML to 'XML'. Commented Oct 30, 2016 at 9:59

1 Answer 1

2
  1. Problem:

Your XML string needs an element you can address. At least a root element should be defined in your XML string. Usually it's called root.

  1. Problem

Your XML is defined in heredocs, which behaves like a string in double quotes. This means all variables are parsed, while the string is stored into $xmlstr.

So, you wont't get valid source code, after storing it to $xmlstr.

You'll need to define this single quotes. Then your variables aren't parsed and replaced. That can be done using nowdoc (avaliable as of PHP 5.3). You'll just have to add two single quote signs (<<<'XML' instead of <<<XML)

So, after all, your xml.php code (as I understand you) would look like this:

<?php
$xmlstr = <<<'XML'
<?xml version='1.0' standalone='yes'?>
<root>
<![CDATA[
    <?php 
    include $_SERVER['DOCUMENT_ROOT'].'xml.php';  
    $template = new SimpleXMLElement($xmlstr); 
    echo $articles->article[0]->name; 
    ?>
]]>
</root>
XML;


$x = new SimpleXMLElement($xmlstr);
print (string)$x; //prints the code as it is defined in $xmlstr

Details to heredoc and nowdoc can be found here: https://secure.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc https://secure.php.net/manual/en/language.types.string.php#language.types.string.syntax.nowdoc

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

Comments

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.