I am trying to create a simple too to get WalkScores for various coordinate pairs using the API. I have two different UI. One has two input text areas, one for the lats and one for lons. It works fine but this is more work for the user. The second UI has each coordinate pair on each line of a text area. The first script below works while the second gives errors even through they use the same functions.
Working script. This takes two fields from a form and creates the arrays to use in the loop. This works but not idea.
<?
$apiKey = 'a55fc4524343bfc9cdd901361092197c';
//comes from form
$lat = $_POST['lat'];
$lon = $_POST['lon'];
// for testing without UI
// $lat = "41.767679,41.346483";
// $lon = "-72.680463,-73.251384";
// for testing without UI
$lats = explode(',', $lat);
$lons = explode(',', $lon);
$address = 'unknown';
for ($i = 0; $i < count($lats); $i++) {
$json = getWalkScore($lats[$i], $lons[$i], $address);
$json_walkScore = json_decode($json);
echo $lats[$i] . "\r\n";
echo $lons[$i] . "\r\n";
echo $json_walkScore->walkscore . "\r\n";
echo $json_walkScore->description . "\r\n";
}
function getWalkScore($lat, $lon, $address)
{
$address = urlencode($address);
$url = "http://api.walkscore.com/score?format=json&address=$address&lat=$lat&lon=$lon&wsapikey=a55fc4524343bfc9cdd901361092197c";
$str = #file_get_contents($url);
return $str;
}
Not working This looks to create identical arrays for use in the loop but returns an error "Notice: Trying to get property 'walkscore' of non-object in..." and only returns the expected output for the last iteration. It works fine for one pair. If I use the hardcoded arrays it works fine..
<?
$apiKey = 'c93ad8c6751f03a31889414b680eec49';
//Data sent from Ajax
$input = $_POST['input'];
//Split string based on new line from text area. Each item is on its own line.
$arr = explode("\n", $input);
//Two arrays to hold data
$lats = [];
$lons = [];
//Break each pair into lat lng and push to arrays
foreach ($arr as $k => $v) {
$coord = explode(",", $v);
$lat = $coord[0];
$lon = $coord[1];
array_push($lats, $lat);
array_push($lons, $lon);
}
//using these hardcoded arrays it works fine.
// $lats = ["41.113676","41.104206"];
// $lons = ["-73.439233","-73.404587"];
//using these hardcoded arrays it works fine.
//Set address to unknown since it is not provided / needed
$address = 'unknown';
//loop over the number of lats, run the get walk score function to return the json data for output
for ($i = 0; $i < count($lats); $i++) {
$json = getWalkScore($lats[$i], $lons[$i], $address);
$json_walkScore = json_decode($json);
// print_r($json_walkScore);
echo $lats[$i] . "\r\n";
echo $lons[$i] . "\r\n";
echo $json_walkScore->walkscore . "\r\n";
echo $json_walkScore->description . "\r\n";
}
function getWalkScore($lat, $lon, $address)
{
$address = urlencode($address);
$url = "http://api.walkscore.com/score?format=json&address=$address&lat=$lat&lon=$lon&wsapikey=a55fc4524343bfc9cdd901361092197c";
$str = #file_get_contents($url);
return $str;
}
Any ideas on why the first is working but the second is not? Let me know if you have questions. Thanks!
After more testing this line
$arr = explode("\n", $input);
needs to be changed to this
$arr = explode("\r\n", $input);
fun... Same EXACT output but it the code decides to work this time.
I have been playing around with a simple php webscraper I've built for a small project of mine. The scraper is running through jobposts on a website and storing all relevant information in an nested array, which I then store in an xml-file. However, the problem is that whenever i run the code it only store the first 79 jobposts and i can't seem to find the problem (I know there are more jobposts with the class I'm searching for).
If anyone can point me in the right direction or have tried something similar themselves, it whould be nice to get a solution :)
I'm running the server locally via. MAMP. Don't know if that could be the problem?
include('simple_html_dom.php');
$Pages = array();
$JobOffers = array();
$html = file_get_html("https://www.jobindex.dk/jobsoegning?q=studiejob");
$NumPage = $html->find('li.page-item');
foreach ($NumPage as $page){
$res = preg_replace("/[^0-9]/", "", $page->plaintext);
$PageNumber = $res.trim();
$PageNumToInt = (int)$PageNumber;
array_push($Pages, $PageNumToInt);
}
$HighestValue = max($Pages);
for($i = 8; $i <= $HighestValue; $i++){
$Newhtml = file_get_html("https://www.jobindex.dk/jobsoegning?page=".$i."&q=studiejob");
$items = $Newhtml->find('div.PaidJob');
foreach ($items as $job){
$RareTitle = $job->find("a", 0)->plaintext;
$CommonTitle = $job->find("a", 1)->plaintext;
$Virksomhed = $job->find("a", 2)->plaintext;
$LinkHref = $job->find("a", 1)->href;
$DisP1 = $job->find("p", 1)->plaintext;
$DisP2 = $job->find("p", 2)->plaintext;
$Dis = $DisP1 . " " . $DisP2;
$date = date("d/m/Y");
$prefix = "JoIn";
echo $RareTitle;
echo $CommonTitle;
echo $Virksomhed;
echo $LinkHref;
echo $Dis;
echo $date;
echo $prefix;
$SingleJob = array($CommonTitle, $RareTitle, $Virksomhed, $Dis, $LinkHref, $date, $prefix);
array_push($JobOffers,$SingleJob);
}}
This code is for saving the job offers in local xml file:
function SaveJobs($JobInfo){
if(file_exists("./xml/JobOffers.xml")){
$i = 1;
foreach ($JobInfo as $jobs){
$xml = new DOMDocument("1.0", "utf-8");
$xml->load("./xml/JobOffers.xml");
// Creating textnode with line break
$textNode = $xml->createTextNode("\n");
// root Element
$root = $xml->getElementsByTagName("job")->item(0);
$root->appendChild($textNode);
// Create Singlejob Element
$SingleJob = $xml->createElement("Jobitem");
//ID Attribute
$DomAtt1 = $xml->createAttribute('ID');
$DomAtt1->value = $i.$jobs[6];
$SingleJob->appendChild($DomAtt1);
//Date Attribute
$DomAtt2 = $xml->createAttribute('Date');
$DomAtt2->value = $jobs[5];
$SingleJob->appendChild($DomAtt2);
// Creating Elements
$TitleElement = $xml->createElement("Title", $jobs[0]);
$SecTitle = $xml->createElement("SecTitle", $jobs[1]);
$Firm = $xml->createElement("Firm", $jobs[2]);
$dis = $xml->createElement("Description", $jobs[3]);
$Linkhref = $xml->createElement("Linkhref", $jobs[4]);
// Append data to SingleJob Element
$SingleJob->appendChild($TitleElement);
$SingleJob->appendChild($SecTitle);
$SingleJob->appendChild($Firm);
$SingleJob->appendChild($dis);
$SingleJob->appendChild($Linkhref);
// Append Singlejob to root and save the changes
$root->appendChild($SingleJob);
$xml->save("./xml/JobOffers.xml");
$i++;
}
}}
I really need some help with this... i just cant make it work.
For now i have this piece of code and it's working fine.
What it does is... retuns all files within a directory according to date in their name.
<?php
header('Access-Control-Allow-Origin: *');
$imagesDir = '';
$images = glob($imagesDir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);
$filteredImages = [];
foreach($images as $image) {
$current_date = date("Ymd");
$file_date = substr($image, 0, 8);
if (strcmp($current_date, $file_date)>=0)
$filteredImages[] = $image;
}
echo json_encode($filteredImages, JSON_UNESCAPED_UNICODE);
?>
But now i need to filter those files (probably before this code is even executed). acording to the string in their name.
files are named in the following manner:
yyyymmdd_xxxxxxx-xxxxxx~yyyymmdd.123456789.jpg
yyyymmdd_xxxxxxx-xxxxxx~yyyymmdd.9.jpg
yyyymmdd_xxxxxxx-xxxxxx~yyyymmdd.458.jpg
i need to filter out only ones that have certain number within that string of numbers at the end (between "." and ".jpg") eg. number 9
$number = 9
i was trying with this piece of code to seperate only that last part of name:
<?php
function getBetween($jpgname,$start,$end){
$r = explode($start, $jpgname);
if (isset($r[1])){
$r = explode($end, $r[1]);
return $r[0];
}
return '';
}
$jpgname = "yyyymmdd_xxxxxxx-xxxxxx~yyyymmdd.12789.jpg";
$start = ".";
$end = ".jpg";
$output = getBetween($jpgname,$start,$end);
echo $output;
?>
and i guess i would need STRIPOS within all of this... but im lost now... :(
You can probably use preg_grep.
It's regex for arrays.
This is untested but I think it should work.
header('Access-Control-Allow-Origin: *');
$imagesDir = '';
$images = glob($imagesDir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);
$find = 9;
$filtered = preg_grep("/.*?\.\d*" . $find . "\d*\./", $images);
The regex will look for anything to a dot then any number or no number, the $find then any or no number again and a dot again.
Is this what you need ? It will give you 123456789
$string = "yyyymmdd_xxxxxxx-xxxxxx~yyyymmdd.123456789.jpg";
$explode = explode(".", $string);
echo ($explode[1]);
Edit -
As per your requirement Andreas's solution seems to be working.
This is what I tried , I changed the find variable and checked.
$images = array("yyyymmdd_xxxxxxx-xxxxxx~yyyymmdd.12789.jpg");
$find = 32;
$filtered = preg_grep("/.*?." . $find . "./", $images);
print_r($filtered);
I'm trying to rewrite a function in javascript to php but it is not working. Maybe someone here can tell me where I am going wrong? Thank you in advance.
Javascript... (working function)
var match;
var chords = ['C','C#','D','D#','E','F','F#','G','G#','A','A#','B','C','Db','D','Eb','E','F','Gb','G','Ab','A','Bb','B','C'];
var chords2 = ['C','Db','D','Eb','E','F','Gb','G','Ab','A','Bb','B','C','C#','D','D#','E','F','F#','G','G#','A','A#','C'];
var chordRegex = /(?:C#|D#|F#|G#|A#|Db|Eb|Gb|Ab|Bb|C|D|E|F|G|A|B)/g;
var rec = /\{(.*?)\}/g; // gets all info between { and }
function transposeUp(){
var html = $('.yui-editor-editable').contents().find('body'); //gets the contents
var matches = $(html).html().match(rec);/////Gets all matches within the html
var text = $(html).html(); // html of the html var
for (var i = 0; i < matches.length; i++) { /////foreach match do
///// initializes variables /////
var currentChord = String(matches[i]); //// sets current chord
currentChord = currentChord.substring(currentChord.indexOf("{") + 1, currentChord.indexOf("}")); //sets current chord cont.
var output = "";
var parts = currentChord.split(chordRegex); // splits currentChord into parts in the chordRegex
var index = 0;
/////////////////////////////////
while (match = chordRegex.exec(currentChord)) { // while the match is equal to the currentChord do
var chordIndex = chords2.indexOf(match[0]); // find the position of the matched chord within the chords2 array
output += parts[index++] + chords[chordIndex + 1]; // build the output
}
output += parts[index];
text = text.replace(matches[i], '{'+output+'}'); //replace the text with the new chords
}
$(html).html(text); // set the html value as the new text
}
PHP...
function transposeUp($songchart){
$chords1 = array('C','C#','D','D#','E','F','F#','G','G#','A','A#','B','C','Db','D','Eb','E','F','Gb','G','Ab','A','Bb','B','C');
$chords2 = array('C','Db','D','Eb','E','F','Gb','G','Ab','A','Bb','B','C','C#','D','D#','E','F','F#','G','G#','A','A#','C');
$chordRegex = "/(?:C#|D#|F#|G#|A#|Db|Eb|Gb|Ab|Bb|C|D|E|F|G|A|B)/";
$matches = preg_match_all('#{.*(.*)}#U', $songchart, $chords);
$chord = $chords[1];
foreach($chord as $key => $value){
$output = '';
$parts = preg_split($chordRegex, $value);
$index = 0;
while(preg_match($chordRegex, $value, $note)){
$chordIndex = strpos($chords2, $note[0]);
$output .= $parts[$index++] . $chords1[$chordIndex + 1];
}
$output .= $parts[$index];
$songchart = preg_replace($value, $output, $songchart);
}
return($songchart);
}
$matches = preg_match_all('#{.*(.*)}#U', $songchart, $chords);
should be:
$matches = preg_match_all('#\{(.*)\}#U', $songchart, $chords);
In your regexp, the first .* was consuming everything inside the braces, so the second one got nothing.
I don't understand the while loop. $value never changes, so how will the loop ever terminate?
$chordIndex = strpos($chords2, $note[0]);
should be:
$chordIndex = array_search($chords2, $note[0]);
since strpos is for searching in strings, not arrays.
$songchart = preg_replace($value, $output, $songchart);
should be:
$songchart = str_replace($value, $output, $songchart);
since $value is not a regular expression.
I'm not sure of everything this is doing, but I suspect it could be simplified by using preg_replace_callback, or maybe even a single str_replace with arrays for the search and replacement arguments.
I have an rss feed, created by Yahoo Pipes and I need to get random post from it. How is it possible to realize this on php?
Read the feed using XML Parser and put it in an array. then, use array_rand to pick a random item from the array.
<?
function load_xml_feed($feed)
{
global $RanVal;
$i= 1;
$FeedXml = simplexml_load_file($feed);
foreach ($FeedXml->channel->item as $topic) {
$title[$i] = (string)$topic->title;
$link[$i] = (string)$topic->link;
$description[$i] = (string)$topic->description;
$i++;
}
$randtopic = rand(2, $i);
$link = trim($link[$randtopic]);
$title = trim($title[$randtopic]);
$description = trim($description[$randtopic]);
$RanVal = array($title,$link,$description);
return $RanVal;
}
$rss = "http://www.sabaharabi.com/rss/rss.xml";
load_xml_feed($rss);
$link = $RanVal[1];
$title = $RanVal[0];
$description = $RanVal[2];
echo "<h1>".$title."</h1><h2>".$link."</h2><p>".$description."</p>";