tags:

views:

249

answers:

2
<?php

include "../music/php/logic/core.php";
include "../music/php/logic/settings.php";
include "../music/php/logic/music.php";
$top = "At world's end";


// create doctype
$dom = new DOMDocument("1.0");

header("Content-Type: text/xml");

?>

<music>
<?php $_xml = "<title>".$top."</title>";
echo $_xml; ?>
</music>

I'm using this code to generate a dynamic XML document. The file is saved as PHP. My problem is that I can't echo php variables into the xml. However I can echo "literal" type text. I can't see anything wrong with my approach, it just doesn't work!

I'm pretty new to XML so I've probably missed something glaringly simple.

I've also tried lines like:

<title><?php echo $top; ?></title>
A: 

I think it's echo($_xml);

Omar Abid
*echo() is not actually a function (it is a language construct), so you are not required to use parentheses with it.* - http://de3.php.net/manual/en/function.echo.php
Gordon
+4  A: 

You don't use DOM this way. You use the DOM API to create the entire document:

$doc   = new DOMDocument();
$books = $doc->createElement( "books" );
$doc->appendChild( $books );
// ...

See:


A more verbose example (generating XHTML with DOM)

// Create head element
$head = $document->createElement('head');
$metahttp = $document->createElement('meta');
$metahttp->setAttribute('http-equiv', 'Content-Type');
$metahttp->setAttribute('content', 'text/html; charset=utf-8');
$head->appendChild($metahttp);

See this tutorial on how to use DOM for XHTML. For reuse of code, you can write your own classes extending DOM classes to get configurable components.


If you don't want to use DOM or want to use plain text for generating the XML, just approach it like any other template, e.g.

<root>
    <albums>
        <album id="<?php echo $albumId; ?>">
            <title><?php echo $title; ?></title>
            ... other elements ...
        </album>
    </albums>
</root>
Gordon
is that the same syntex as Javascript?
YsoL8
Your question is a bit confusing to me. Nothing in this answer has anything to do with javascript? Are you talking about `->`?
middus
@YsoL8 Syntax? No. PHP's syntax is obviously different from that of JavaScript. If you are refering to the methods exposed by the DOM API though, then the answer is yes. DOM is a language agnostic W3C interface recommendation and implemented in many languages. See http://www.w3.org/DOM/
Gordon
Sorry, the first section reminded me of it. Not relevent
YsoL8
I'm following the plain text approach and making progress. I'll comment when I've tried a couple of things.
YsoL8
Right, this is working now. Question: my includes aren't included. do you know why? last comment
YsoL8
@YsoL8 No, sorry. Not without seeing your code. You might want to make this into a new question.
Gordon