user2649054
user2649054

Reputation: 3

Hyperlink in XML Data Doesn't Display in PHP File

I have a PHP file that reads an XML file and uses a for loop to display the data as HTML5 <article> objects. All that works like a champ. The problem I'm having seems to be in relation to the data in the XML file itself. My data is similar to this:

<articles>
  <article>
    <num>1</num><text>This is one.</text>
  </article>
  <article>
    <num>2</num><text>This is <a href='./two.htm'>two</a>.</text>
  </article>
  <article>
    <num>3</num><text>This is three.</text>
  </article>
</articles>

I load the XML like this:

$xml = simplexml_load_file("./articles_test.xml");

The output looks like this:

This is one.
This is .
This is three.

I've tried escaping, quoting, using HTML entity names and a number of other things to no avail. Appreciate the help. Thanks.

Upvotes: 0

Views: 155

Answers (2)

Mr. Polywhirl
Mr. Polywhirl

Reputation: 48693

CDATA - text data that should not be parsed by the XML parser.

<article>
    <num>2</num>
    <text>
        <![CDATA[
            This is <a href='./two.htm'>two</a>.
        ]]>
    </text>
</article>

Edit

May I suggest PHP's Dom, it is very powerful as it allows you to easily parse HTML content. Here is a popular pros-cons question that you may be interested in. What's the difference between PHP's DOM and SimpleXML extensions?

$doc = new DomDocument();
$file = "../articles_test.xml";
$doc->load($file);
$xPath = new DomXPath($doc);
$article_text = $xPath->query("//article/text")->item(1);
echo $article_text->nodeValue;

Upvotes: 2

Matt
Matt

Reputation: 5428

You need to use asXML() to output:

<?php
$string = <<<XML
<?xml version='1.0'?> 
<articles>
  <article>
    <num>1</num><text>This is one.</text>
  </article>
  <article>
    <num>2</num><text>This is <a href='./two.htm'>two</a>.</text>
  </article>
  <article>
    <num>3</num><text>This is three.</text>
  </article>
</articles>
XML;

$xml = simplexml_load_string($string);

print_r($xml->asXML());

See it in action here: http://codepad.org/EW9yQcdM

Upvotes: 0

Related Questions