I am new to PHP and I am trying to work on this one problem where the middle of a URL changes.
For instance using this fake URL,
$url = 'http://www.bobsplace.com/events/georgetown/12354544233123';
I need to be able to substitute "georgetown" out with a random variable.
So I guess I need to like slice the URL after events, have a variable where "georgetown" would be, and then have the rest of the URL continue after it. I hope I am making as much sense as possible.
Alright,
I tried all these and still go errors, but most likely it is due to my current coding. I am entering the entire thing in now.
<?
// This URL only shows future events
$url = 'https://graph.facebook.com/192674347443031/events?access_token=153420758043439|66d692f0e73ad17d939d9d9c-1045402872|8VHLfMb3gYY0p9fnT7wMS8Q9Krc&expires_in=0&since=yesterday' ;
$event_id = get_post_custom_values('facebook_id');
$url = str_replace('/192674347443031/', '/' . $event_id . '/', $url);
$json = file_get_contents($url) ;
$data = json_decode( $json,true) ;
//var_dump($data) ;
$sorted_array = array_reverse($data['data'], TRUE) ;
foreach ($sorted_array as $key => $value) {
//print_r($value) ;
?>
<? echo "<li><a href='http://facebook.com/event.php?eid=". $value['id'] . "' target='_blank'>" ;
echo "<h2>" . $value['name'] . "</h2>" ;
echo "</a>" ;
echo " (" . $value['location'] .") <br />" ;
echo date("F j, Y, g:i a" , strtotime($value['start_time'])) . " to " . date("F j, Y, g:i a" , strtotime($value['end_time'])) ;?>
<div class="moreinfo">
<? echo "<a href='http://facebook.com/event.php?eid=". $value['id'] . " ' target='_blank'>" ;
echo "<b>" . 'More info' . "</b>" ;
echo "</a>" ;?>
</div>
<? echo "</li>";
}
?>
The errors I keep getting are now saying my array_reverse() should be an array. And also invalid argument foreach()
Now this is not the entire code on that page, but this is the snippet that is giving me problems.
you can do :
$url = 'http//:www.bobsplace.com/events/georgetown/12354544233123';
$my_var = 'foobar';
$url = str_replace("georgetown", $my_var, $url );
or :
$url = 'http//:www.bobsplace.com/events/georgetown/12354544233123';
$my_var = 'foobar';
$temp = explode( '/' , $url );
$temp[4] = $my_var;
$url = implode( '/' , $temp );
First one will replace by name , second one by position in URL.
I think you're trying to say that you want to replace the text "georgetown". If that's correct, the following code should work (make sure you've defined $replace to what you want to replace it with):
$url = str_replace('/georgetown/', '/' . $replace . '/', $url);
$variable = 'place'; //e.g. georgetown
$url = 'http:www.bobsplace.com/events/'.$variable.'/12354544233123';
I think this is what you're asking for.
Related
I'm working on a script that will retrieve API information of the 'near earth objects' from NASA's website. User selects date, api grabs the information and displays it. How do I fix the foreach in this script? would appreciate some help with this.
$jsonAsteroids = file_get_contents("https://api.nasa.gov/neo/rest/v1/feed?start_date=2018-08-01&end_date=2018-08-04&api_key=NNKOjkoul8n1CH18TWA9gwngW1s1SmjESPjNoUFo");
$data = json_decode($jsonAsteroids, true);
echo "<h4>Retrieving the first element (i.e. \"links\") of the JSON structure</h4>";
var_dump( $data["links"]);
echo "<h4>Retrieving the first element (i.e. \"next\") inside the \"links\" element</h4>";
echo( $data["links"]["next"]);
You were very close. Your main issue was that you used json_decode(..., true); which gives you an array, but then used the object->property syntax instead of object['property']. My suggestion is to use json_decode without the 2nd argument in this case.
Finally, your 2nd foreach was malformed.
<?php
$result = file_get_contents("https://api.nasa.gov/neo/rest/v1/feed?start_date=2018-08-01&end_date=2018-08-04&api_key=NNKOjkoul8n1CH18TWA9gwngW1s1SmjESPjNoUFo");
$data = json_decode($result);
foreach ($data->near_earth_objects as $date => $objects) {
echo "<p>" . count($objects) . " objects detected on $date</p>";
echo "<ol>";
foreach ($objects as $object) {
echo "<li>" . $object->name . " <a href='" . $object->nasa_jpl_url . "'>" . $object->nasa_jpl_url . "</a><br>";
echo "Diameter of the object: " . $object->estimated_diameter->meters->estimated_diameter_min . "-" . $object->estimated_diameter->meters->estimated_diameter_max . " metres<br>";
echo "<ul>";
foreach ($object->close_approach_data as $close_approach) {
echo "<li>Close approach: " . $close_approach->close_approach_date . " traveling at a velocity of " . $close_approach->relative_velocity->kilometers_per_hour . " km/h " . "missing " . $close_approach->orbiting_body . " by " . $close_approach->miss_distance->kilometers . " km</li> ";
}
echo "</ul>";
}
echo "</ol>";
}
I have this PHP code which I'm trying to extract some information but I stopped to href step:
$site = "http://www.sports-reference.com/olympics/countries";
$site_html = file_get_html($site);
$country_dirty = $site_html->getElementById('div_countries');
foreach($country_dirty->find('img') as $link){
$country = $link->alt;
$link_country = "$site/$country";
$link_country_html = file_get_html($link_country);
$link_season = $link_country_html->getElementById('div_medals');
foreach($link_season->find('a') as $season){
echo $link_year_season = $season->href . "\n";
//echo $link_season = strstr ($link_year_season,'summer') . "\n";
}
}
The variable $link_year_season gets me the following output:
/olympics/countries/AFG/summer/2012/
/olympics/athletes/ba/nesar-ahmad-bahawi-1.html
/olympics/athletes/ni/rohullah-nikpai-1.html
/olympics/countries/AFG/summer/2008/
/olympics/athletes/ba/nesar-ahmad-bahawi-1.html
/olympics/athletes/ni/rohullah-nikpai-1.html
/olympics/countries/AFG/summer/2004/
/olympics/countries/AFG/summer/1996/
/olympics/countries/AFG/summer/1988/
/olympics/countries/AFG/summer/1980/
/olympics/countries/AFG/summer/1972/
.....
I'd like to know if it is possible to get only this output:
/olympics/countries/AFG/summer/2012/
/olympics/countries/AFG/summer/2008/
/olympics/countries/AFG/summer/2004/
/olympics/countries/AFG/summer/1996/
/olympics/countries/AFG/summer/1988/
/olympics/countries/AFG/summer/1980/
/olympics/countries/AFG/summer/1972/
You should be able to use this regex to check that the link starts with /olympics/countries/AFG/summer/ then a number and a /.
foreach($link_season->find('a') as $season){
if(preg_match('~^/olympics/countries/AFG/summer/\d+/~', $season->href)) {
echo $link_year_season = $season->href . "\n";
//echo $link_season = strstr ($link_year_season,'summer') . "\n";
}
}
Demo: https://regex101.com/r/bZ1vP3/1
You could also pull the current year by capturing the number after summer (presuming that is a year, first regex just checks for number this one is stricter)..
foreach($link_season->find('a') as $season){
if(preg_match('~^/olympics/countries/AFG/summer/(\d{4})/~', $season->href, $year)) {
echo $link_year_season = $season->href . "\n";
//echo $link_season = strstr ($link_year_season,'summer') . "\n";
echo 'The year is ' . $year[1] . "\n";
}
}
If the season also can vary you could do (?:summer|winter) which would allow for summer or winter to be the fourth directory.
$refPointer = $site_to_be_extracted . $a->href;
echo $refPointer . '<br>';
generates in output (Chrome browser):
http://www.hackingwithphp.com/1/1/0/is-this-book-for-you
You would expect the following line to generate a correct <a> tag. That is a correct link
print '<a href=' . $refPointer . '>' . $a . '</a>';
Instead it generates in output:
localhost/1/1/0/is-this-book-for-you
So both the protocol (HTTP) and the $site_to_be_extracted (www.hackingwithphp.com) are lost. And replaced by "localhost"
Why? What could be the problem
This is the function where it's all happening. Now it works fine
include('simple_html_dom.php');
.
.
function createChapterContent ($site_to_be_extracted, $chapter_to_be_extracted) {
$html = file_get_html($chapter_to_be_extracted);
$refPointer;
foreach($html->find('ol') as $ol) {
foreach($ol->find('li') as $li) {
// echo '<br>' . $li->innertext ;
foreach($li->find('a') as $a) {
// Original. Causing the reported problem
// $refPointer = $site_to_be_extracted . $a->href;
// echo $refPointer . '<br>';
// changed to (see below). Now the output is correct
// Why?
$a->href = $site_to_be_extracted . $a->href;
$refPointer = $a->href;
print '<a href=' . $refPointer . '>' . $li->innertext . '</a>' . '<br>';
break;
};
}
}
I have the following php code:
$skizzar_masonry_item_width = $masonry_item_width;
$skizzar_masonry_item_padding = $masonry_item_padding;
$skizzar_double_width_size = $masonry_item_width*2 +$masonry_item_padding;
$output .= '<style>.skizzar_masonry_entry.skizzar_ma_double, .skizzar_masonry_entry.skizzar_ma_double img {width:'.$skizzar_double_width_size.'}</style>';
return $output;
For some reason though, the value of $skizzar_double_width_size is not being added into the $output - is there a way to echo a value in an output variable?
As #Rizier123 mentioned, ensure you initialise any string variables before trying to append to them.
$var = '';
$var .= 'I appended';
$var .= ' a string!';
I would also like to strongly discourage you from using inline styles as well as generating them with inline PHP. Things get very messy very quickly.
In a situation like this you need to check that all the variables you are using in the calculation are valid before you panic.
So try
echo 'before I use these values they contain<br>';
echo '$masonry_item_width = ' . $masonry_item_width . '<br>';
echo '$masonry_item_padding = ' . $masonry_item_padding . '<br>';
$skizzar_masonry_item_width = $masonry_item_width;
$skizzar_masonry_item_padding = $masonry_item_padding;
$skizzar_double_width_size = $masonry_item_width*2 +$masonry_item_padding;
echo 'after moving the fields to an unnecessary intemediary field<br>';
echo '$skizzar_masonry_item_width = ' . $skizzar_masonry_item_width . '<br>';
echo '$skizzar_masonry_item_padding = ' . $skizzar_masonry_item_padding . '<br>';
echo '$skizzar_double_width_size = ' . $skizzar_double_width_size . '<br>';
$output .= '<style>.skizzar_masonry_entry.skizzar_ma_double, .skizzar_masonry_entry.skizzar_ma_double img {width:'.$skizzar_double_width_size.'}</style>';
echo $output;
This should identify which fields are causing you problems.
Also while testing always run with display_errors = On It saves so much time in the long run.
I am trying to set location markers. The code below is not looping through the results and displays only the first row. I tested the query and result outside of Google Maps and it work.
var addresses = [
<?php
while($row = mysql_fetch_array($results)) {
echo '"'.$row['company'].', '. $row['address'].', ' . $row['city'] . ', ' . $row['state'] . ', ' . $row['zip'] .'",';
}
?>
];
This is what you should do:
<?php
...
$array = array();
while ($row = mysql_fetch_assoc($results)) {
$array[] = array(
'company'=>$row['company'],
'address'=>$row['address'],
'lat'=>$row['latitude'],
'lng'=>$row['longitude'],
); // add what ever cels you need
}
$json_string = json_encode($array);
echo 'var addresses=' . $json_string . ';';
...
?>
If you keep having problems, please post the javascript part of the code; this is just the part where you print an object (or array) in a format that javascript can read.