views:

93

answers:

4

Hi everybody!

I am loading an xml in php via simplexml_load_file().

I load the file with that:

$xml = simplexml_load_file('flash/datas/datas.xml');

And the access my content like that:

$descText = $xml->aboutModule->chocolaterie->desc

The text from desc is well registred in my $descText, but all the <br/> of the text disappear... So my long text is on a single line, not so good :-/

Do you know how to solve that? Is there a special traitement to do one the $xml var? Or someting else?

Thank you in advance for your help!

+1  A: 

Take a look of this.

There is a way to get back HTML tags. For example:

<?xml version="1.0"?>
<intro>
    Welcome to <b>Example.com</b>!
</intro>

This is the PHP code:

<?php
// I use @ so that it doesn't spit out content of my XML in an
// error message if the load fails. The content could be
// passwords so this is just to be safe.
$xml = @simplexml_load_file('content_intro.xml');
if ($xml) {
    // asXML() will keep the HTML tags but it will also keep the parent tag <intro> so I strip them out with a str_replace. You could obviously also use a preg_replace if you have lots of tags.
    $intro = str_replace(array('<intro>', '</intro>'), '', $xml->asXML());
} else {
    $error = "Could not load intro XML file.";
}
?>
Cristian
Great! Thank you for your help!It work perfectly, even with just the ->asXML() command. I am amazed to discover that stack overflow isn't any urban legend! So fast answsers, thank very much to you all!
daviddarx
+1  A: 

If you have control over your source XML, you may find it better to store the description as character data, i.e. in a CDATA wrapper, rather than mixing your XML with HTML.

For example, instead of:

...
<desc>
    This is a description<br /> with a break in it
</desc>
...

...do something like:

...
<desc>
<![CDATA[
    This is a description<br /> with a break in it
]]>
</desc>

But if you haven't, then as Casidiablo says, you'll have to grab the content of the <desc> element as XML.

Matt Gibson
Yeah, I wholeheartedly agree that mixing HTML with XML = bleh.
Josh Davis
+1  A: 

Two ways to make it work.

The right one

Do not store those <br/>. Store the real actual newlines, e.g.

<desc>
    Line 1.
    Line 2.
</desc>

Then use nl2br() to replace newlines with HTML tags. This is assuming your description does not normally contain markup. If it does, use CDATA sections as proposed in another answer.

The other one

$descText = strip_tags($xml->aboutModule->chocolaterie->desc->asXML(), '<br /><br/>');
Josh Davis
This one is better! Thank you!
daviddarx
A: 

Hi,

Better you can use the following code to replace the BR tags to new line chars.

preg_replace("/(\s*)+/", "\n", $input);

OR

you can convert the description content to "htmlentities" and then turn back to "htmlspecialchars"

VAC-Prabhu