Setting variable variables inside a foreach - php

I am trying to use $value inside the $feed_title variable. And generate all 200 $feed_title variables.
What I am trying to accomplish would look like this:
Feed Url: http://something.com/term/###/feed
Feed Title: Some Title
Where the ### varies from 100-300.
I am using the following code, and getting the urls, but not sure how to get the titles for each feed:
$arr = range(100,300);
foreach($arr as $key=>$value)
{
unset($arr[$key + 1]);
$feed_title = simplexml_load_file('http://www.something.com/term/'
. ??? . '/0/feed');
echo 'Feed URL: <a href="http://www.something.com/term/' . $value
. '/0/feed">http://www.something.com//term/' . $value
. '/0/feed</a><br/> Feed Category: ' . $feed_title->channel[0]->title
. '<br/>';
}
Do I need another loop inside of the foreach? Any help is appreciated.

If you want to get the title of a page, use this function:
function getTitle($Url){
$str = file_get_contents($Url);
if(strlen($str)>0){
preg_match("/\<title\>(.*)\<\/title\>/",$str,$title);
return $title[1];
}
}
Here's some sample code:
<?php
function getTitle($Url){
$str = file_get_contents($Url);
if(strlen($str)>0){
preg_match("/\<title\>(.*)\<\/title\>/",$str,$title);
return $title[1];
}
}
$arr = range(300,305);
foreach($arr as $value)
{
$feed_title = getTitle('http://www.translate.com/portuguese/feed/' . $value);
echo 'Feed URL: http://www.translate.com/portuguese/feed/' . $value . '<br/>
Feed Category: ' . $feed_title . '<br/>';
}
?>
This gets the title from translate.com pages. I just limited the number of pages for faster execution.
Just change the getTitle to your function if you want to get the title from xml.

Instead of using an array created with range, use a for loop as follows:
for($i = 100; $i <= 300; $i++){
$feed = simplexml_load_file('http://www.something.com/term/' . $i . '/0/feed');
echo 'Feed URL: http://www.something.com/term/' . $i . '/0/feed/ <br /> Feed category: ' . $feed->channel[0]->title . '<br/>';
}

Related

Parsing json with a nested element

does not work with a nested element
the elements of the first level are output, and the nested array with data is not read, as it is possible to get values - id, title and location?
<?php
function removeBomUtf8($s){
if(substr($s,0,3)==chr(hexdec('EF')).chr(hexdec('BB')).chr(hexdec('BF'))){
return substr($s,3);
}else{
return $s;
}
}
$url = "https://denden000qwerty.000webhostapp.com/opportunities.json";
$content = file_get_contents($url);
$clean_content = removeBomUtf8($content);
$decoded = json_decode($clean_content);
while ($el_name = current($decoded)) {
// echo 'total = ' . $el_name->total_items . 'current = ' . $el_name->current_page . 'total = ' . $el_name->total_pages . '<br>' ;
echo ' id = ' . $el_name->data[0]->id . ' title = ' . $el_name->data.title . ' location = ' . $el_name->data.location . '<br>' ;
next($decoded);
}
?>
$el_name->data[0]->id is correct
$el_name->data.title is not
you see the difference?
and $decoded is the root (no need to iterate over it) - you want to iterate over the data children
<?php
foreach($decoded->data as $data)
{
$id = (string)$data->id;
$title = (string)$data->title;
$location = (string)$data->location;
echo sprintf('id = %s, title = %s, location = %s<br />', $id, $title, $location);
}

Getting a random object from an array in PHP

First and foremost, forgive me if my language is off - I'm still learning how to both speak and write in programming languages. How I can retrieve an entire object from an array in PHP when that array has several key, value pairs?
<?php
$quotes = array();
$quotes[0] = array(
"quote" => "This is a great quote",
"attribution" => "Benjamin Franklin"
);
$quotes[1] = array(
"quote" => "This here is a really good quote",
"attribution" => "Theodore Roosevelt"
);
function get_random_quote($quote_id, $quote) {
$output = "";
$output = '<h1>' . $quote["quote"] . '.</h1>';
$output .= '<p>' . $quote["attribution"] . '</p>';
return $output;
} ?>
<?php
foreach($quotes as $quote_id => $quote) {
echo get_random_quote($quote_id, $quote);
} ?>
Using array_rand and var_dump I'm able to view the item in the browser in raw form, but I'm unable to actually figure out how to get each element to display in HTML.
$quote = $quotes;
$random_quote = array_rand($quote);
var_dump($quote[$random_quote]);
Thanks in advance for any help!
No need for that hefty function
$random=$quotes[array_rand($quotes)];
echo $random["quote"];
echo $random["attribution"];
Also, this is useless
<?php
foreach($quotes as $quote_id => $quote) {
echo get_random_quote($quote_id, $quote);
} ?>
If you have to run a loop over all the elements then why randomize hem in the first place? This is circular. You should just run the loop as many number of times as the quotes you need in output. If you however just need all the quotes but in a random order then that can simply be done in one line.
shuffle($quotes); // this will randomize your quotes order for loop
foreach($quotes as $qoute)
{
echo $quote["quote"];
echo $quote["attribution"];
}
This will also make sure that your quotes are not repeated, whereas your own solution and the other suggestions will still repeat your quotes randomly for any reasonably sized array of quotes.
A simpler version of your function would be
function get_random_quote(&$quotes)
{
$quote=$quotes[array_rand($quotes)];
return <<<HTML
<h1>{$quote["quote"]}</h1>
<p>{$quote["attribution"]}</p>
HTML;
}
function should be like this
function get_random_quote($quote_id, $quote) {
$m = 0;
$n = sizeof($quote)-1;
$i= rand($m, $n);
$output = "";
$output = '<h1>' . $quote[$i]["quote"] . '.</h1>';
$output .= '<p>' . $quote[$i]["attribution"] . '</p>';
return $output;
}
However you are not using your first parameter-$quote_id in the function. you can remove it. and call function with single parameter that is array $quote
Why don't you try this:
$quote = $quotes;
$random_quote = array_rand($quote);
$random = $quote[$random_quote];
echo '<h1>' . $random["quote"] . '.</h1><br>';
echo '<p>' . $random["attribution"] . '</p>';
Want to create a function:
echo get_random_quote($quotes);
function get_random_quote($quotes) {
$quote = $quotes;
$random_quote = array_rand($quote);
$random = $quote[$random_quote];
return '<h1>' . $random["quote"] . '.</h1><br>'.'<p>' . $random["attribution"] . '</p>';
}
First, you dont need the $quote_id in get_random_quote(), should be like this:
function get_random_quote($quote) {
$output = "";
$output = '<h1>' . $quote["quote"] . '.</h1>';
$output .= '<p>' . $quote["attribution"] . '</p>';
return $output;
}
And I cant see anything random that the function is doing. You are just iterating through the array:
foreach($quotes as $quote_id => $quote) {
echo get_random_quote( $quote);
}
According to http://php.net/manual/en/function.array-rand.php:
array_rand() Picks one or more random entries out of an array, and
returns the key (or keys) of the random entries.
So I guess $quote[$random_quote] should return your element, you can use it like:
$random_quote = array_rand($quotes);
echo get_random_quote($quote[$random_quote]);

Need to create li with list of different links using php explode method

here is my working php explode code for NON links:
<?php
$textarea = get_custom_field('my_custom_output');
$array = explode(',',$textarea);
$output = ''; // initialize the variable
foreach ($array as $item) {
$item = trim($item); // clear off white-space
$output .= '<li>' . $item . '</li>';
}
?>
<ul>
<?php print $output; ?>
</ul>
..and the code which defines "my_custom_output", which I input into my textarea field:
text1,text2,text3,etc
..and the finished product:
text1
text2
text3
etc
So that works.
Now what I want to do is make text1 be a link to mywebsite.com/text1-page-url/
I was able to get this far:
<?php
$textarea = get_custom_field('my_custom_output');
$array = explode(',',$textarea);
$output = ''; // initialize the variable
foreach ($array as $item) {
$item = trim($item); // clear off white-space
$output .= '<li class="link-class"><a title="' . $item . '" href="http://mywebsite.com/' . $item_links . '">' . $item . '</a></li>';
}
?>
<ul>
<?php print $output; ?>
</ul>
Now, I would like $item_links to define just the rest of the url. For example:
I want to put input this into my textarea:
text1:text1-page-url,text2:new-text2-page,text3:different-page-text3
and have the output be this:
text1
text2
..etc (stackoverflow forced me to only have two links in this post because I only have 0 reputation)
another thing I want to do is change commas to new lines. I know the code for a new line is \n but I do not know how to swap it out. That way I can put this:
text1:text1-page-url
text2:new-text2-page
text3:different-page-text3
I hope I made this easy for you to understand. I am almost there, I am just stuck. Please help. Thank you!
Just split the $item inside your loop with explode():
<?php
$separator1 = "\n";
$separator2 = ":";
$textarea = get_custom_field('my_custom_output');
$array = explode($separator1,$textarea);
$output = ''; // initialize the variable
foreach ($array as $item) {
list($item_text, $item_links) = explode($separator2, trim($item));
$output .= '<li class="link-class"><a title="' . $item_text . '" href="http://mywebsite.com/' . $item_links . '">' . $item_text . '</a></li>';
}
?>
<ul>
<?php print $output; ?>
</ul>
And choose your string separators so $item_text, $item_links wouldn't contain them.
After you explode the string you could loop through again and separate the text and link into key/values. Something like...
$array_final = new array();
$array_temp = explode(',', $textarea);
foreach($array_temp as $item) {
list($text, $link) = explode(':', $item);
$array_final[$text] = $link;
}
foreach($array_final as $key => $value) {
echo '<li>'.$key.'</li>';
}
to change comma into new line you can use str_replace like
str_replace(",", "\r\n", $output)

PHP iteration foreach, omitting characters from last iteration

I'm tying to iterate through an array, assembling a string to return each time.
My question is how can I omit the comma on the last iteration of the array, or if there is only one element to the array? I'm not sure what this operation would be called as my coding skills are very rudimentary, so I've not had much luck searching for an answer. Even help knowing this basic detail would be much appreciated.
this is the result I'd like:
{ image : 'http://www.site.com/path/to/file/image1.jpg', title : 'Some title and caption' url : 'http://www.site.com/path/to/file/image1.jpg' },
{ image : 'http://www.site.com/path/to/file/image1.jpg', title : 'Some title and caption' url : 'http://www.site.com/path/to/file/image1.jpg' },
{ image : 'http://www.site.com/path/to/file/image1.jpg', title : 'Some title and caption' url : 'http://www.site.com/path/to/file/image1.jpg' }
Note the lack of a trailing comma.
Below is the php Im using to generate the strings. It will always include a trailing comma which is causing me all sorts of greif.
//snipit
$i = 1;
$a = '';
foreach ($pages as $go)
{
$title = ($go['media_title'] == '') ? ' ' : $go['media_title'];
$caption = ($go['media_caption'] == '') ? ' ' : $go['media_caption'];
$a .= "{ image :'" . BASEURL . GIMGS . "/$go[media_file]', title : '{$title}, {$caption}', url: '" . BASEURL . GIMGS . "/$go[media_file]' }";
$a .= ",\n";
$i++;
return $a;
}
Many thanks for your experience,
orionrush
$a[] = "{ image :'" . BASEURL . GIMGS . "/$go[media_file]', title : '{$title}, {$caption}', url: '" . BASEURL . GIMGS . "/$go[media_file]' }";
and use it by
return implode(",\n", $a);
You should really use json_encode().
$data = array();
foreach ($pages as $go) {
$title = ($go['media_title'] == '') ? ' ' : $go['media_title'];
$caption = ($go['media_caption'] == '') ? ' ' : $go['media_caption'];
$data[] = array(
'image' => BASEURL . GIMGS . '/' . $go['media_file'],
'title' => $title . ', ' . $caption,
'url' => BASEURL . GIMGS . '/' . $go['media_file']
);
}
echo json_encode($data);
foreach ($pages as $go){
$return[] = json_encode($go);
}
return implode(",\n", $return);
do what you like in the foreach, the implode will comma separate the lines like you want
just chop the end off with substr:
return substr($a, 0, -3);

Parse JSON data created by php json_encode

I want to be able to parse the following json data. It was constructed from a php array using jsonencode. I've added the json below to help you understand it. I'd like to be able to display the json in a bulleted form. It show two records with associated category array and tags array. Im open to using any libraries to help.
{"0":{"categories":[{"name":"Football Club","slug":"football-club"}],"tags":[{"name":"England","slug":"england"},{"name":"EPL","slug":"epl"},{"name":"Europe","slug":"europe"},{"name":"Champions","slug":"champions"}],"ID":"908","post_author":"78350","post_date":"2010-10-18 10:49:16","post_title":"Liverpool Football Club","post_content":"Content goes here...","post_name":"liverpoolfc","guid":"http://www.liverpoolfc.tv","post_type":"post","comment_count":"0","comment_status":"open","relevance_count":0},"1":{"categories":[{"name":"Football Club","slug":"football-club"}],"tags":[{"name":"England","slug":"england"},{"name":"EPL","slug":"epl"},{"name":"Europe","slug":"europe"},{"name":"Champions","slug":"champions"}],"ID":"907","post_author":"78350","post_date":"2010-10-18 10:49:16","post_title":"Everton Football Club","post_content":"Content goes here","post_name":"evertonfc","guid":"http://www.evertonfc.tv","post_type":"post","comment_count":"0","comment_status":"open","relevance_count":0}}
I want to be able to parse it and display like this.
Liverpool Football Club
Content goes
here
Categories
Football Club
Tags
England
EPL
UPDATE: Sorry i need to parse it in javascript.
Try this:
$json = '{"0":{"categories":[{"name":"Football Club","slug":"football-club"}],"tags":[{"name":"England","slug":"england"},{"name":"EPL","slug":"epl"},{"name":"Europe","slug":"europe"},{"name":"Champions","slug":"champions"}],"ID":"908","post_author":"78350","post_date":"2010-10-18 10:49:16","post_title":"Liverpool Football Club","post_content":"Content goes here...","post_name":"liverpoolfc","guid":"http://www.liverpoolfc.tv","post_type":"post","comment_count":"0","comment_status":"open","relevance_count":0},"1":{"categories":[{"name":"Football Club","slug":"football-club"}],"tags":[{"name":"England","slug":"england"},{"name":"EPL","slug":"epl"},{"name":"Europe","slug":"europe"},{"name":"Champions","slug":"champions"}],"ID":"907","post_author":"78350","post_date":"2010-10-18 10:49:16","post_title":"Everton Football Club","post_content":"Content goes here","post_name":"evertonfc","guid":"http://www.evertonfc.tv","post_type":"post","comment_count":"0","comment_status":"open","relevance_count":0}}';
$array = json_decode($json, true);
foreach ($array as $item) {
echo '<ul>' . PHP_EOL;
echo '<li>' . $item['post_title'] . '</li>' . PHP_EOL;
echo '<li>' . $item['post_content'] . '</li>' . PHP_EOL;
/* Display Categories */
echo '<li>Categories' . PHP_EOL;
echo '<ul>' . PHP_EOL;
if (!empty($item['categories'])) {
foreach ($item['categories'] as $category) {
echo '<li>' . $category['name'] . '</li>' . PHP_EOL;
}
} else {
echo '<li>No Categories Available</li>' . PHP_EOL;
}
echo '</ul>' . PHP_EOL;
echo '</li>' . PHP_EOL;
/* Display Tags */
echo '<li>Tags' . PHP_EOL;
echo '<ul>' . PHP_EOL;
if (!empty($item['tags'])) {
foreach ($item['tags'] as $tag) {
echo '<li>' . $tag['name'] . '</li>' . PHP_EOL;
}
} else {
echo '<li>No Tags Available</li>' . PHP_EOL;
}
echo '</ul>' . PHP_EOL;
echo '</li>' . PHP_EOL;
echo '</ul>' . PHP_EOL;
}
UPDATE Are you asking on how to do this in PHP or in Javascript/jQuery? You didn't quite explain what you were doing with it.
UPDATE Here it is using Javascript/jQuery: http://jsfiddle.net/wgjjR/
//<div id="container"></div>
//var json = {}; // this is your JSON object
var container = $('#container'), html = [];
for (var key in json) {
var item = json[key];
html.push('<ul>');
html.push('<li>' + item.post_title + '</li>');
html.push('<li>' + item.post_content + '</li>');
html.push('<li>Categories<ul>');
for (var cat in item.categories) {
cat = item.categories[cat];
html.push('<li>' + cat.name + '</li>');
}
html.push('</ul></li>');
html.push('<li>Tags<ul>');
for (var tag in item.tags) {
tag = item.tags[tag];
html.push('<li>' + tag.name + '</li>');
}
html.push('</ul></li>');
html.push('</ul>');
}
$json = json_decode($inputJson, true);
foreach($json as $key => $value)
{
// do somethig
}
Use json_decode
$json = json_decode($some_json, true);
$element1 = $json["item"]["element1"];
$element2 = $json["item"]["element2"];
Repeat to extract all the values you require.

Categories