conditioning in XML parsing - PHP - php

Its been a while since the last time I was coding, and I am a little rusty. I am trying to parse an xml file and having a problem with the condition. Spent hours trying to figure out where is the problem, but without success...
PHP CODE:
<div id="gallery">
<?php
$cat_img="images/cat.png";
$logo_path="logos/";
$file = simplexml_load_file('stores.xml');
$old_cat="";
foreach($file->store as $store){
if($store->cat != $old_cat){
echo "<img id='cat' src='".$cat_img."'><div id='cat_text'>".$store->cat."</div><br>";
$old_cat=$store->cat;
}
echo "<div id='store'><img id='store_img' src='".$logo_path.$store->logo."' alt='logo'><br>";
echo "<store_name>".$store->name."</store_name>";
echo "<phone>".$store->phone."</phone><phone>טל: </phone></div>";
}
?>
</div>
STORES.XML
<?xml version="1.0" encoding="UTF-8"?>
<stores>
<store><logo>renuar.jpg</logo>
<name>renuar</name>
<phone>052-6059962</phone>
<cat>clothing</cat></store>
<store><logo>yoop.jpg</logo>
<name>YOOP</name>
<phone>08-6601451</phone>
<cat>clothing</cat></store>
....
</stores>
The idea is to print every store, when category changes it should print the category divider and keep printing the stores. Somehow the condition is always true and I have no idea why...
p.s
If anyone has a better idea on how to divide the categories, a different method, I would be happy to hear.
Thanks!!!

$store->cat will be SimpleXMLElement object and two object will not be same even with same category name. You need to cast it to string for comparison
Like (string) $store->cat, try this:
<?php
$cat_img = "images/cat.png";
$logo_path = "logos/";
$file = simplexml_load_file('test.xml');
$old_cat = "";
foreach ($file->store as $store) {
if ((string) $store->cat != $old_cat) {
echo "<img id='cat' src='" . $cat_img . "'><div id='cat_text'>category: " . $store->cat . "</div><br>";
$old_cat = (string) $store->cat;
}
echo "<div id='store'><img id='store_img' src='" . $logo_path . $store->logo . "' alt='logo'><br>";
echo "<store_name>" . $store->name . "</store_name>";
echo "<phone>" . $store->phone . "</phone><phone>טל: </phone></div>";
}
?>

Related

PHP Looping through a JSON file Illegal string offset error

I have a json file data, cache.txt. When I try to write the data I retrieved from it I get this error Illegal string offset for all fields.
I get the data but I cannot read fields, I don't know why
The file Data
s:729:"[{"id":"787","name":"XXY","release":"2007","Language":"Spanish","cover":"upload\/photos\/2019\/06\/sKRTzoEjRPCeHWsCrcHi_19_c12db8f07c6acb75a430a0c63c4f7e8d_image.jpg"},{"id":"638","name":"Barfi","release":"2012","Language":"Hindi","cover":"upload\/photos\/2019\/04\/uJD7t2q3XQcsOjSORv1c_25_eff4e484426302484d8de738dcb99470_image.jpg"},{"id":"937","name":"Secretary","release":"2002","Language":"English","cover":"upload\/photos\/2019\/01\/Secretary.jpg"},{"id":"829","name":"Love Meet Hope","release":"2016","Language":"English","cover":"upload\/photos\/2019\/01\/Love-Meet-Hope.jpg"},{"id":"412","name":"Daughters Of Darkness","release":"1971","Language":"English","cover":"upload\/photos\/2019\/01\/Daughters-Of-Darkness.jpg"}]";
<?php
WritePopularMovies();
function WriteData()
{
$movies = json_decode(GetData(),true);
for($i=0;$i < 5;$i++)
{
echo "<div class='col-exs-6 col-xs-4 col-sm-3 col-md-3'>";
echo "<figure>";
echo "<a href='" . $movies[$i]['id'] . "'>";
echo "<img src='" . $movies[$i]['cover'] ."' alt='".$movies[$i]['name'] .
"' class='responsive-img' style='height:250px;width:170px'>";
echo "</a>";
echo "<h6 title=". $movies[$i]['name'] ."><a href='". $movies[$i]['id']."'>".
$movies[$i]['name']."</a></h6>";
echo "<p>". $movies[$i]['genre']. "(".$movies[$i]['language'].")| ".
$movies[$i]['release'] ."</p>";
echo "</figure>";
echo "</div>";
}
}
function GetData() {
$data = array();
$file = $_SERVER['DOCUMENT_ROOT'] .'/cache.txt';
$data = unserialize(file_get_contents($file));
return json_encode($data,true);
}
?>
I tried to solve it but with no luck, so I will appreciate your help.
Many thanks
In your GetData() you are reading the data and then encoding it...
return json_encode($data,true);
this isn't necessary and stops the next part working, just return the raw data
return $data;

PHP -displaying 12 items of an associative array with specific key and value

<?php
foreach($catalog as $id=> $item) {
echo get_item_html($id,$item);
}
// here is the functions page code :
function get_item_html($id,$item){
$output = "<li><a href='#'><img src='"
. $item["img"] . "' alt='"
. $item["title"] . "' />"
. "<p>View Details</p>"
. "</a></li>";
return $output;
}
?>
I have used it for displaying product categories i checked several time but I did find any error but it display undefined variable
please help me to find out this solution

XML Skip 'wrong' event type

I have a certain BLOATED XML file that i use to generate a Gallery with some few information about the Picture. Besides of the Actual needed NEW there are plenty of entries with OLD, adding more pictures, but creating also duplicate entries.
<result>
<event>
<date>2015-04-14T22:19:02+02:00</date>
<type>OLD</type>
<value1>AAA</value1>
<id>changingIDwhatever</id>
<profile>
<url>/domainpart/SPECIFICNAME/?w=</url>
<name>SPECIFICNAME</name>
<value2>BBB</value2>
<value3>CCC</value3>
<value4>DDD</value4>
<image>
<url>http://domain.tld/path/to/the/image/320.jpg?1234-ab1cd2e345fg6789</url>
<width>320</width>
</image>
</profile>
</event>
<event>
<date>2015-04-14T22:19:02+02:00</date>
<type>NEW</type>
<value1>AAA</value1>
<id>changingIDwhatever</id>
<profile>
<url>/domainpart/ANOTHERNAME/?w=</url>
<name>ANOTHERNAME</name>
<value2>BBB</value2>
<value3>CCC</value3>
<value4>DDD</value4>
<image>
<url>http://domain.tld/path/to/the/image/320.jpg?1234-ab1cd2e345fg6789</url>
<width>320</width>
</image>
</profile>
</event>
<event>
<date>2015-04-14T22:19:02+02:00</date>
<type>NEW</type>
<value1>AAA</value1>
<id>changingIDwhatever</id>
<profile>
<url>/domainpart/SPECIFICNAME/?w=</url>
<name>SPECIFICNAME</name>
<value2>BBB</value2>
<value3>CCC</value3>
<value4>DDD</value4>
<image>
<url>http://domain.tld/path/to/the/image/320.jpg?1234-ab1cd2e345fg6789</url>
<width>320</width>
</image>
</profile>
</event>
</result>
I do generate everything in a pretty neat layout in a very basic way. As i have really NO knowledge at all about php, i usually base on skriptpieces i find that are kind of put together in a way that the outcome mostly is the way i need it.
<?php
//###################Config Start#########################
$memberid = "123456";
$maxAnzahl = 50;
$zaehler = 0;
$baseURL = "http://www.domain.tld";
//###################Config End#########################
$feed = simplexml_load_file('http://key:keypass#www.domain.tld/news/xml');
$events = $feed->events;
foreach ($events->event as $event) {
echo "<div class='4u'>";
echo "<article class='box style2'>";
if ($event->type == "newMember") {
echo "<a href='".$baseURL.$event->profile->url.$memberid."' class='image featured' target='_blank'><img src='" . $event->profile->image->url . "' alt='' /> </a>";
} else {
echo "<a href='".$baseURL.$event->profile->url.$memberid."' class='image featured' target='_blank'><img src='" . $event->image->url . "' alt='' /> </a>";
}
echo "<h3><a href='".$baseURL.$event->profile->url.$memberid."'>" . $event->profile->name . "</a></h3>";
echo "</article>";
echo "</div>";
$zaehler = $zaehler + 1;
if ($zaehler == $maxAnzahl) {
break;
}
}
?>
Would be someone able to tell me how i could specify now in that skript how to SKIP all OLD ?
Kind Regards
Caylean
I have found the solution myself sigh I was blind to it, till i got the first reply, checked my question AGAIN and saw a marker that I normally wanted to change everywhere to make it CLEAR what i needed.
In my initial question was a line "if ($event->type == "newMember") {" Normally i had to change it to "NEW" like in my example, to help ppl who wanted to help, to see it more easy.... Well, now i saw it and it made everything clear to me.
Changing the code like:
<?php
//###################Config Start#########################
$memberid = "123456";
$maxAnzahl = 50;
$zaehler = 0;
$baseURL = "http://www.domain.tld";
//###################Config End#########################
$feed = simplexml_load_file('http://key:keypass#www.domain.tld/news/xml');
$events = $feed->events;
foreach ($events->event as $event) {
if ($event->type == "NEW") {
echo "<div class='4u'>";
echo "<article class='box style2'>";
echo "<a href='".$baseURL.$event->profile->url.$memberid."' class='image featured' target='_blank'><img src='" . $event->profile->image->url . "' alt='' /> </a>";
echo "<h3><a href='".$baseURL.$event->profile->url.$memberid."'>" . $event->profile->name . "</a></h3>";
echo "</article>";
echo "</div>";
} else {
echo "";
}
$zaehler = $zaehler + 1;
if ($zaehler == $maxAnzahl) {
break;
}
}
?>
Gives me exactly the Images and Content i was looking for. For some reason i had already the solution in the code, but it was somehow messed up.
Thank you anyways for the help and thoughts!
For this kind of tasks like query the XML structure I prefer to use XPATH.
Try like this. I hope works for you.
<?php
// Get the XML
//###################Config Start#########################
$memberid = "123456";
$maxAnzahl = 50;
$zaehler = 0;
$baseURL = "http://www.domain.tld";
//###################Config End#########################
$source = file_get_contents('http://key:keypass#www.domain.tld/news/xml');
// DOM document Creation
$doc = new DOMDocument;
$doc->loadXML($source);
// DOM XPath Creation
$xpath = new DOMXPath($doc);
// Get all NEW events ONLY
$events = $xpath->query('//result/event[text()="NEW"]');
// Count number of events
printf('There is %d events<br />', $events->length);
// List all events
for($i = 0; $i < ($events->length); $i++) {
$event = $events->item($i);
}
?>
Would be someone able to tell me how i could specify now in that skript how to SKIP all OLD ?
You can introduce a condition right at the beginning of your foreach-loop that checks if the actual $event entry is to be skipped (filtered-out) and if so, skip to the next entry in loop:
foreach ($events->event as $event) {
$skip = $event->type != 'NEW';
if ($skip) {
continue;
}
...
Please see continue (and its sister break) to control loop structures in PHP.

Nested foreach statements are invalid. Help?

Please forgive the extreme-beginner style of coding. I'm working with PHP and JSON strings from an API for the first time.
What I'm trying to do here, which obviously doesn't work if you look through it, is print out multiple movie results that the user is searching for. This is a search results page - with a movie poster and some key details next to each item.
One of the things I want next to each result is a list of the first 5 actors listed in the movie, as "Starring" and then any directors listed in the movie as "Director".
The problem is no doubt the fact that I've nested foreach statements. But I don't know any other way of doing this.
Please please the simplest answer would be the best for me. I don't mind if it's bad practice, just whatever solves it quickest would be perfect!
Here's the code:
// Check if there were any results
if ($films_result == '["Nothing found."]' || $films_result == null) {
}
else {
// Loop through each film returned
foreach ($films as $film) {
// Set default poster image to use if film doesn't have one
$backdrop_url = 'images/placeholder-film.gif';
// Loop through each poster for current film
foreach($film->backdrops as $backdrop) {
if ($backdrop->image->size == 'thumb') {
$backdrop_url = $backdrop->image->url;
}
}
echo '<div class="view-films-film">
<img src="' . $backdrop_url . '" alt="' . strtolower($film->name) . '" />
<div class="view-films-film-snippet">
<h2>' . strtolower($film->name) . '</h2>
<img src="images/bbfc-' . strtolower($film->certification) . '.png" alt="" />
<h3>Starring</h3>
<p>';
$num_actors = 0;
foreach ($films[0]->cast as $cast) {
if ($cast->job == 'Actor') {
echo '' . $cast->name . ' ';
$num_actors++;
if ($num_actors == 5)
break;
}
}
echo ' </p>
<h3>Director</h3>
<p>';
foreach ($films[0]->cast as $cast) {
if ($cast->job == 'Director') {
echo '' . $cast->name . ' ';
}
}
echo ' </p>
</div>
</div>';
// End films
}
}
An example of the result would be this:
with line 120 being foreach ($films[0]->cast as $cast) { and line 131 being foreach ($films[0]->cast as $cast) {
Why are you using $films[0] when you're in a foreach ($films as $film)? You should be using $film->cast right? And you should dump $film at the start of your loop with var_dump and inspect it - make sure $cast is an array and is populated. If it's not, work back from there.

PHP and HTML Echo

I want to query a result from a table. The problem I run into is if the text is very long it will not auto-wrap to another line"best way i can think to explain it". It displays the text on one line and will go way off to the side of the page if the text is long. How can I get the text to space correctly. Thanks
here is my code:
<?php
echo "<div class=\"item_list2\">";
$get_items = "SELECT * FROM items WHERE category='Art'";
$result = mysql_query($get_items);
//loop! loops through the multiple results of the $get_items query
while($item = mysql_fetch_array($result, MYSQL_ASSOC)){
echo "<b>" . $item['item'] . "</b><br/>" . $item['email'] . "<br/>";
echo $item['price'] . "</b><br/>" . $item['category'] . "</b><br/>" . $item['extra'];
echo "<br/><a href='manage.php?delete=" . $item['id'] . "'><small>[Delete]</small></a><br/><br/>";
}
echo "</div>";
?>
Just use CSS to break it.
.container
{
word-wrap: break-word;
}
maybe you want to add..
nl2br($item['extra']);

Categories