Passing PHP variables to XML in a .php file
<?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>
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:
- http://www.ibm.com/developerworks/library/os-xmldomphp/
- http://www.tonymarston.net/php-mysql/dom.html
- https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-10878_11-6141415.html
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>
You can store your XMl string in a .php file then render it to get final formatted XMl string. In many cases simpler than playing with XMl writers
File template.php
<root>
<albums>
<album id="<?php echo $data['albumId']; ?>">
<title><?php echo $data['title']; ?></title>
... other elements ...
</album>
</albums>
</root>
Render
function render($template, array $data)
{
ob_start();
include $template;
return ob_get_clean();
}
I think it's echo($_xml);
精彩评论