I have the following output (via link) which displays the var_dump of some XML im generating:
http://bit.ly/aoA3qY
At the very bottom of the page you will see some output, generated by this code:
foreach ($xml->feed as $entry) {
$title = $entry->title;
$title2 = $entry->entry->title;
}
echo $title;
echo $title2;
For some reason $title2 only outputs once, where there are multiple entries?
Im using $xml = simplexml_load_string($data); to create the xml.
You re-assign a value to $title and $tile2 in each iteration of the foreach loop. After the loop is finished only the last assigned value is accessible.
Possible alternatives:
// print/use the values within the loop-body
foreach ($xml->feed as $entry) {
$title = $entry->title;
$title2 = $entry->entry->title;
echo $title, ' ', $title2, "\n";
}
// append the values in each iteration to a string
$title = $title2 = '';
foreach ($xml->feed as $entry) {
$title .= $entry->title . ' ';
$title2 .= $entry->entry->title . ' ';
}
echo $title, ' ', $title2, "\n";
// append the values in each iteration to an array
$title = $title2 = array();
foreach ($xml->feed as $entry) {
$title[] = $entry->title;
$title2[] = $entry->entry->title;
}
var_dump($title, $title2);
Related
I'm trying to parse DOM with Simple HTML DOM Parser in PHP. Parsed content are movies, so I want to get every genre there is, but when i run my code I only get the last genre, not all. My code looks like this:
if ($obj) {
foreach($obj as $key => $data) {
$item['url'] = 'http://geo.saitebi.ge/movie/' . $page;
$item['poster'] = 'http://geo.saitebi.ge/web/ka/img/movies/' . $page . '/240x340/' . $page . '.jpg';
$item['geotitle'] = $data->find('div.movie-item-title', 0)->plaintext;
$item['englishtitle'] = $data->find('div.movie-item-title-en', 0)->plaintext;
$item['year'] = $data->find('div.movie-item-year', 0)->plaintext;
foreach($data->find('a.movie-genre-item') as $genre) {
$item['genres'] = $genre->plaintext . ', ';
}
$item['description'] = $data->find('div.movie-desctiption-more', 0)->plaintext;
$item['imdb_rating'] = $data->find('a.imdb_vote', 0)->plaintext;
$item['imdb_id'] = trim(substr($data->find('a.imdb_vote',0)->href, strrpos($data->find('a.imdb_vote',0)->href, '/') + 1));
}
}
As you see I'm getting content as array. Then inside it I run another foreach loop to get all genre items but it only gets last genre item. What is wrong in my code?
You are just overwriting the last set of data each time. You need to set it to blank and then append it using .= each time, like...
$item['genres'] = '';
foreach($data->find('a.movie-genre-item') as $genre) {
$item['genres'] .= $genre->plaintext . ', ';
}
The code are saving the same '$genre->plaintext' in $item with key 'genres'
so the same key replace the values every loop.
foreach($data->find('a.movie-genre-item') as $genre) {
$item['genres'] = $genre->plaintext . ', ';
}
May $item['genres] can be an associative array.. i mean:
foreach($data->find('a.movie-genre-item') as $genre) {
if ( !isset($item[$genre]) ) {
$item[$genre] = array();
}
array_push($item[$genre],$genre->plaintext);
}
Here is genre code which you have to update
// Here is you genre code
$movie_genre='';
foreach($data->find('a.movie-genre-item') as $genre) {
$movie_genre .= $genre->plaintext . ',';
}
// Here you can use rtrim for removing last comma from genre
$item['genres'] = rtrim($movie_genre,',');
I am parsing a very large XML file with XMLReader.
$reader = new XMLReader;
$reader->open('products.xml');
$dom = new DOMDocument;
$xpath = new DOMXpath($dom);
while ($reader->read() && $reader->name !== 'product') {
continue;
}
A while loop is used to display relevant data based on user input as well as building arrays with XML values.
while ($reader->name === 'product') {
$node = $dom->importNode($reader->expand(), TRUE);
if ($xpath->evaluate('number(price)', $node) > $price_submitted) {
$category = $xpath->evaluate('string(#category)', $node);
$name = $xpath->evaluate('string(name)', $node);
$price = $xpath->evaluate('number(price)', $node);
// Relevant search results displayed here:
echo "Category: " . $category . ". ";
echo "Name: " . $name . ". ";
echo "Price: " . $price . ". ";
$nameArray[] = $name;
}
$reader->next('product');
}
The foreach loop below uses the array that is built in the while loop above. I need these values (displayed in this foreach loop below) to appear BEFORE the while loop above displays the relevant search results. With XMLReader, you can only execute one while loop for each time you parse the XML, and I don't want to parse it twice because of memory and overhead issues. What is the best way to do this?
foreach ($nameArray as $names) {
echo $names . " ";
}
Well… there are not many options. The most effectiv straight-forward approach is to store category/name/price in array instead of outputting them directly:
<?php
$data = array();
while ($reader->name === 'product') {
$node = $dom->importNode($reader->expand(), TRUE);
if ($xpath->evaluate('number(price)', $node) > $price_submitted) {
$category = $xpath->evaluate('string(#category)', $node);
$name = $xpath->evaluate('string(name)', $node);
$price = $xpath->evaluate('number(price)', $node);
$data[] = array($category, $name, $price);
$nameArray[] = $name;
}
$reader->next('product');
}
foreach ($nameArray as $names) {
echo $names . " ";
}
foreach ($data as $datum) {
// Relevant search results displayed here:
echo "Category: " . $datum[0] . ". ";
echo "Name: " . $datum[1] . ". ";
echo "Price: " . $datum[2] . ". ";
}
In case that doesn't work memory-wise (you mentioned that XML file is really large) you should use db- or file-backed temporary storage
Hi there i am trying to combine two loops of foreach but i have a problem.
The problem is that the <a href='$link'> is same to all results but they must be different.
Here is the code that i am using:
<?php
$feed = file_get_contents('http://grabo.bg/rss/?city=&affid=16090');
$rss = simplexml_load_string($feed);
$doc = new DOMDocument();
#$doc->loadHTML($feed);
$tags = $doc->getElementsByTagName('link');
foreach ($tags as $tag) {
foreach($rss as $r){
$title = $r->title;
$content = $r->content;
$link = $tag->getAttribute('href');
echo "<a href='$link'>$title</a> <br> $content";
}
}
?>
Where i my mistake? Why it's not working and how i make it work properly?
Thanks in advance!
Both loops were going through different resources so you are just simply cross joining all records in them.
This should work to get the data you need:
<?php
$feed = file_get_contents('http://grabo.bg/rss/?city=&affid=16090');
$rss = simplexml_load_string($feed);
foreach ($rss as $key => $entry) {
if ($key == "entry")
{
$title = (string) $entry->title;
$content = (string) $entry->content;
$link = (string) $entry->link["href"];
echo "<a href='$link'>$title</a><br />" . $content;
}
}
I'm trying to display values from this xml feed:
http://www.scorespro.com/rss/live-soccer.xml
In my PHP code I have the following loop but it does not display the results on my page:
<?php
$xml = simplexml_load_file("http://www.scorespro.com/rss/live-soccer.xml");
echo $xml->getName() . "<br>";
foreach($xml->children() as $item)
{
echo $item->getName() . ": " . $item->name . "<br>";
}
?>
For some reason it only shows:
rss
channel:
I'm fairly new to how XML works so any help would be much appreciated.
You can get actual data from $xml->channel->item so use like below
$items = $xml->channel->item;
foreach($items as $item) {
$title = $item->title;
$link = $item->link;
$pubDate = $item->pubDate;
$description = $item->description;
}
DEMO.
you can use below code
$dom = new DOMDocument;
$dom->loadXML($url);
if (!$dom) {
echo 'Error while parsing the document';
exit;
}
$xml = simplexml_import_dom($dom);
$data = $xml->channel->item;
http://www.managerleague.com/export_data.pl?data=transfers&output=xml&hide_header=0
These are player sales from a browser game. I want to save some fields from these sales. I am fetching that xml with curl and storing on my server. Then do the following:
$xml_str = file_get_contents('salespage.xml');
$xml = new SimpleXMLElement($xml_str);
$items = $xml->xpath('*/transfer');
print_r($items);
foreach($items as $item) {
echo $item['buyerTeamname'], ': ', $item['sellerTeamname'], "\n";
}
The array is empty and i cant seem to get anything from it. What am i doing wrong?
There is no reason to use cURL or XPath for that. You can do
$url = 'http://www.managerleague.com/export_data.pl?data=transfers&output=xml&hide_header=0';
$transfers = new SimpleXMLElement($url, NULL, TRUE);
foreach($transfers->transfer as $transfer) {
printf(
"%s transfered from %s to %s\n",
$transfer->playerName,
$transfer->sellerTeamname,
$transfer->buyerTeamname
);
}
Live Demo
You forgot a slash in your xpath:
$xml_str = file_get_contents('salespage.xml');
$xml = new SimpleXMLElement($xml_str);
$items = $xml->xpath('/*/transfer');
print_r($items);
foreach($items as $item) {
echo $item->buyerTeamname, ': ', $item->sellerTeamname, "\n";
}
<?php
$xml = simplexml_load_file("test.xml");
echo $xml->getName() . "<br />";
foreach($xml->children() as $child)
{
echo $child->getName() . ": " . $child . "<br />";
}
?>
Is this what you want?