Gus Gus - 9 days ago 5
PHP Question

Displaying neatly formatted XML document with PHP?

I'm building a classified adverts site and my listings are stored in an XML document. I load this document in to the listings page of my site using simplexml and then use foreach to display these.

At current everything works fine its just the formatting of the output I'd like to improve. Each listing is stacked on top of each other as such:

LISTING
LISTING
LISTING
LISTING


I would like them to be like this -
LISTING LISTING LISTING LISTING and then once the edge of the column is reached, start on the next line.

Any help appreciated!
Thanks in advance!

Relevant PHP code here -

<?php
// Loading the XML file
$xml = simplexml_load_file("listings.xml");

foreach($xml->listing as $listing)
{
echo "<u>Item ID:</u> ".$listing->id."<br />";
echo '<img src="images/' . $listing->image . '"width="200" height="225">';
echo "<br>Item: ".$listing->title." <br />";
echo "Description: ".$listing->description." <br />";
echo "Seller: ".$listing->seller." <br />";
echo "Price: ".$listing->price." <br /><br />";
}
?>


Relevant XML document here -

<?xml version="1.0" encoding="utf-8"?>
<advertlistings>
<listing>
<id>1</id>
<title>Another fucking cooker</title>
<description>Best cooker of them all</description>
<image>fractal pyramid.jpg</image>
<price>3400</price>
<seller>MJ420</seller>
</listing>

<listing>
<id>2</id>
<title>Shit cooker</title>
<description>Shite cooker of the world</description>
<image>1479991892439-1307203880.jpg</image>
<price>2735</price>
<seller>MJ420</seller>
</listing>
</advertlistings>


Please ignore the descriptions etc, over the period of making this website cookers have become my worst enemy :p

Answer

See my comment for my general thoughts, but the direct (and I think not very useful) answer is something like this:

foreach($xml->listing as $listing)
{
    echo '<div style="float:left">';
    echo "<u>Item ID:</u> ".$listing->id."<br />";
    echo '<img src="images/' . $listing->image . '"width="200" height="225">';
    echo "<br>Item: ".$listing->title." <br />";
    echo "Description: ".$listing->description." <br />";
    echo "Seller: ".$listing->seller." <br />";
    echo "Price: ".$listing->price." <br /><br />";
    echo '</div>';
}
echo '<div style="clear:both"></div>';

It will look similar to what you wanted, but there are many problems, it should not be done this way, and I can't explain in an answer why.

Keywords: styles/css (in general), inline vs external css, cross-site scripting, xxe, templating, mvc, etc...

Comments