1

I need a way to include an external XML file in PHP which does not use simplexml tags. Furthermore, I'd also need it to integrate with other imported XMLs, hence removing file headers as <?XML version...>

Basically have a PHP class which includes methods to dynamically create XML elements based on user-input. For example, I could create a node called "test", set "id=1" as attribute and add child nodes to it. What I basically need, is a way to extract further XML content from other files and have my PHP script recognize it, hence being able to call methods on this imported code. I tried using php's fopen() function but, although it would print the imported XML to the screen, it would not validate and signal an error as soon as the imported code began. I cannot use simpleXML extension for two main reasons. Firstly, the entire class is written using Pre-PHP5 XML handling, and I cannot re-write the whole thing from scratch as it is part of a team-project, secondly, such class features methods which could not be replicated with simpleXML extension.

This is the XML I generate: <?xml version="1.0"?> <ga><dsa>hea</dsa><sda>eh</sda></ga> <gg><ds>he</ds><sd>eh</sd></gg> And it returns: Illegal Content, Line 3 Column 1, highliting the "<" of the "gg" tag... (Which, by the way, is the part imported from the external file.)

This is a snippet of the code used to print imported XML:

$file = simplexml_load_file($url);
     foreach($file as $key => $value) {
         echo "<" . $key . ">" .  $value . "</" . $key . ">\n";
      }

How can this be done?

Additional note: Yes, the server suppors PHP 5 (5.2.6), but the code was written in pre-php5.

Gordon
  • 312,688
  • 75
  • 539
  • 559
max0005
  • 210
  • 4
  • 9
  • Ok, I basically have a PHP class which includes methods to dynamically create XML elements based on user-input. For example, I could create a node called "test", set "id=1" as attribute and add child nodes to it. What I basically need, is a way to extract further XML content from other files and have my PHP script recognize it, hence being able to call methods on this imported code. I tried using php's fopen() function but, although it would print the imported XML to the screen, it would not validate and signal an error as soon as the imported code began. – max0005 Jul 18 '11 at 10:15
  • I cannot use simpleXML extension for two main reasons. Firstly, the entire class is written using Pre-PHP5 XML handling, and I cannot re-write the whole thing from scratch as it is part of a team-project, secondly, such class features methods which could not be replicated with simpleXML extension. – max0005 Jul 18 '11 at 10:18
  • Done... Any further suggestions? – max0005 Jul 18 '11 at 10:32
  • In fact, using simpleXml prints an XML error to my screen. That is because the rest of the methods do not implement such extension, hence probably resulting in some kind of conflict. – max0005 Jul 18 '11 at 10:37
  • This is the XML I generate: ` heaeh heeh` And it returns: Illegal Content, Line 3 Column 1, highliting the "<" of the "gg" tag... (Which, by the way, is the part imported from the external file.) – max0005 Jul 18 '11 at 10:44
  • You mean and ? In any case, how coudl I solve the problem? I should tell PHP to print the file as a child node of the tag, am I correct? – max0005 Jul 18 '11 at 10:50

1 Answers1

2

Judging from your comments I'd say you get an error because a valid XML document needs a root element. You XML has two: <ga> and <gg>, which means the XML is invalid and cannot be parsed.

You should fix your XML by adding a root element. Then the parsing errors will go away.

Another option would be to load the snippet as a document fragment with DOM:

$brokenXML = <<< XML
<?xml version="1.0"?>
<ga><dsa>hea</dsa><sda>eh</sda></ga>
<gg><ds>he</ds><sd>eh</sd></gg>
XML;

$dom = new DOMDocument;
$fragment = $dom->createDocumentFragment();
$fragment->appendXML(trim(str_replace('<?xml version="1.0"?>', '', $brokenXML)));
echo $dom->saveXml($fragment);

Output:

<ga><dsa>hea</dsa><sda>eh</sda></ga>
<gg><ds>he</ds><sd>eh</sd></gg>

But note that this is still not a complete XML document because it misses a root element.

If you want to import a DOM Tree into another, you can use DOMDocument::importNode. To use that with the fragment above, you would do

$dom2 = new DOMDocument('1.0', 'utf-8');
$dom2->appendChild($dom2->createElement('foo'))
        ->appendChild($dom2->importNode($fragment, true));

echo $dom2->saveXml();

That would result in

<?xml version="1.0" encoding="utf-8"?>
<foo><ga><dsa>hea</dsa><sda>eh</sda></ga>
<gg><ds>he</ds><sd>eh</sd></gg></foo>

If you have an existing document you want to import to, you would simply do

$dom2 = new DOMDocument;
$dom2->load('existingFile.xml');
$dom2->documentElement->appendChild($dom2->importNode($fragment, true));

This would append the fragment as the last child of the root node. If you want to have it somewhere else on the DOM tree, you would have to traverse the DOM tree with Xpath or getElementsByTagName or getElementsById or the childNodes property on the various nodes and then append to that node instead.

Gordon
  • 312,688
  • 75
  • 539
  • 559
  • Dear Gordon, Thanks for your answer. At the present, I use createElement to add nodes, and saveXML() to display the created XML. At this point, when I add an XML fild I need a way to have them isnerted as child nodes of the root. How could I do this? Woudl the createDocumentFragment() you mentioned work? Is it supported by pre-PHP5 servers? – max0005 Jul 18 '11 at 13:11
  • @max see update. And No, this will not work with PHP < 5. In fact, any PHP version below PHP 5.3 is dead. No longer supported. Time to upgrade. – Gordon Jul 18 '11 at 13:28
  • I've resorted to a kind of hybrid thing inspired from what you suggested. Basically, I am importing the whole file, stripping it of its header and attempting to create it as a leaf of the XML tree. For example, suppose my external xml was. hello; I am creating a node on my xml tree and setting the external file as its content. Unfortunately, what I'm getting is: <gg> <ds>he</ds><sd>eh</sd></gg> What is that string of things supposed to rappresent? – max0005 Jul 18 '11 at 13:37
  • @max When you try to add markup as nodeValue, DOM will encode any `<` and `>` because it doesnt recognize it as element delimiter but character data. This is expected behavior and perfectly correct. If you want to import a DOM tree you have to use the import function or create a fragment. See above and [my answer here](http://stackoverflow.com/questions/4979836/noob-question-about-domdocument-in-php/4983721#4983721) to learn more about how DOM works. – Gordon Jul 18 '11 at 13:46
  • @max Cant you just use what I told you to use? Understand the concept instead of hacking around please. – Gordon Jul 18 '11 at 13:56
  • My problem is, I already have some XML on the DOM, and I have to add to it. With that method I am appending to 'foo' only the imported XML... At least, that's what I'm getting... – max0005 Jul 18 '11 at 14:06
  • OK, I think, in the end, I got it. :) I am first importing the external XML file, in the meantime creating the root node, then using my methods to dynamically add further nodes. Thanks so much for having so much patience on a newbie like me. ^^ Is there any way I can like add to your reputation or similar? (Again, I'm new here, so I'm not familiar with how this works.) – max0005 Jul 18 '11 at 14:13
  • @max actually all you have to do is load the fragment. Then you load the existing XML you want to append the fragment to. In the example above I didnt load existing XML but created a foo document. And to that I imported the fragment. So all you have to do is exchange the foo document with the document you want to import into, traverse it to the node you want to append to and then append. If my answer solves your question, you can tick the green checkmark right below the voting controls to accept the answer. – Gordon Jul 18 '11 at 14:19