Home > database >  PHP / XML output does not show any content in client browser
PHP / XML output does not show any content in client browser

Time:05-05

I have the following PHP code:

process.php script for XML output format

<?php
$name='Imran';
$nick='Alkan';
header('Content-type: text/xml charset=utf-8');
?>
<echo1>
    <name><?php echo $name; ?></name>
    <nick><?php echo $nick; ?></nick>
</echo1>

and index.php for showing values of name and nick tags

<?php
$xml=file_get_contents('process.php');
$xml=simplexml_load_string($xml);
echo $xml->name.' '.$xml->nick;
?>

CodePudding user response:

it does show output: a single whitespace.

in

    <name><?php echo $name; ?></name>

the <?...?> is interpreted as a xml comment, and thus the <name> has no text content (it contains a xml comment, but not any text) thus (string)$xml->name is emptystring. it's the same with (string)$xml->nick, so your echo $xml->name.' '.$xml->nick; boils down to echo ((string)$xml->name).' '.((string)$xml->nick); which boils down to just echo ' '; , thus in your browser a single whitespace is printed :)

the problem here is that file_get_contents() does not do what you think it does, it does not actually execute the contents of the file as php.. i think you're looking for require(), try

$xml=require('process.php');

which does practically what you incorrectly believed file_get_contents does, eg

$xml=eval(file_get_contents('process.php'));

CodePudding user response:

As the name suggests, file_get_contents() does not execute scripts, it only opens files.

The most straightforward way to run simple PHP code is require. However, since your code prints to standard output you also need to capture that:

ob_start();
require 'process.php';
$xml = ob_end_clean();

Beware that the script also generates HTTP headers, so you need to do this before you generate any output.

Said that, this is the most inconvenient design. Why don't you just put your code in a regular function?

  • Related