Fastest way to retrieve part from JSON in my case - php

Now, I use strstr to get data from external JSON file. I'm not sure if it's the fastest way to do that what I want and I can't test because json_decode don't work in my code.
$before = '"THIS":"';
$after = '","date"';
$data = strstr(substr($url, strpos($url, $before) + strlen($before)), $after, true)
and with json_decode:
$address = file_get_contents('http://json.link/?something=Hello');
$data = json_decode($address);
echo $data->data->THIS;
Now, when I replace my first code with second I get:
Notice: Trying to get property of non-object
All my code:
$text = "a lot of text";
$text_split = array(0 => '');
$number = 0;
$words = explode(' ', $text);
foreach($words as $word)
{
if(strlen($text_split[$number]) + strlen($word) + 1 > 500)
{
++$number;
$text_split[$number] = '';
}
$text_split[$number] .= $word.' ';
}
foreach($text_split as $texts)
{
$text_encode = rawurlencode($texts);
$address = file_get_contents('http://json.link/?something='.$text_encode);
$data = json_decode($address);
echo $data->data->THIS;
}
What should in do in that case? Keep using strstr or replace all code to work with json_decode (maybe because execution time is faster?)? If the second option, how I can make json_decode work here? Thanks!
... and sorry for bad english.
LE:
If I replace $address = file_get_contents('http://json.link/?something='.$text_encode); with $address = file_get_contents('http://json.link/?something=Hello'); I get VALID result for "Hello" text but 10 times. I guess because it's in a foreach.

json_decode is the suggested method to work with JSON data. Here I think you are trying to access an invalid property in JSON object.
$data = json_decode($address);
echo $data->data->THIS;
I guess you need $data->date instead of $data-data?

you have to access the specific key value like this
$json = '{"success":true,"msg":"success","data":{"THIS":"thing I need","date":"24.03.2014","https":false}}';
$d=json_decode($json,true);
echo $d['data']['THIS'];

Related

Why does only one PHP Script work while the other gives an error only looping over last item of array?

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.

str ireplace PHP parts of url

I have a html doc that has links in it.
Example :
http://mysite1.com/test/whatIwant/Idontwantthis
http://mysite1.com/test/whatIwant2/Istilldontwantthis
http://mysite1.com/test/whatIwant3/Idontwantthiseither
I want to replace these with:
http://myothersite.com/whatIwant
http://myothersite.com/whatIwant2
http://myothersite.com/whatIwant3
How can I do this? I feel like the only way is to use str_ireplace to get the value that I want and append it to the other link, I just can't seem to remove the part after the value that I want.
I use:
$var= str_ireplace("http://mysite1.com/test/", "http://myothersite.com/", $var);
But then I get the after value still on the link:
http://myothersite.com/whatIwant/Idontwantthis
I tried and now am turning to the community for help.
Thanks
Oh and they are enclosed in the tag with class and other attributes, all I need to change is the URL as explained above.
The links are not in an array they are being edited from a javascript file so they will be in a large variable as text.
$examples =
'http://mysite1.com/test/whatIwant/Idontwantthis http://mysite1.com/test/whatIwant2/Istilldontwantthis http://mysite1.com/test/whatIwant2/Istilldontwantthis
http://mysite1.com/test/whatIwant3/Idontwantthiseither'
;
Edit: using your updated example, you can split those URLs up by the whitespace between them:
$examples = 'http://mysite1.com/test/whatIwant/Idontwantthis http://mysite1.com/test/whatIwant2/Istilldontwantthis http://mysite1.com/test/whatIwant2/Istilldontwantthis http://mysite1.com/test/whatIwant3/Idontwantthiseither';
$examples = explode(' ', $examples);
Alternative example array:
$examples = array(
'http://mysite1.com/test/whatIwant/Idontwantthis',
'http://mysite1.com/test/whatIwant2/Istilldontwantthis',
'http://mysite1.com/test/whatIwant3/Idontwantthiseither'
);
Regex solution:
$pattern = '/^(?:http|https):\/\/.+\/.*\/(.+)\/.*$/Um';
$replace = 'http://myothersite.com/$1';
foreach($examples as $example) {
echo preg_replace($pattern, $replace, $example);
}
Non-regex solution:
foreach($examples as $example) {
// remove the original domain name
$first = str_ireplace('http://mysite1.com/test/', '', $example);
// prepend the new domain name with the first part of the remaining URL
// e.g. strip everything after the first slash
echo 'http://myothersite.com/' . explode('/', $first)[0];
}
Note: using explode(...)[0] is array dereferencing, and is supported in PHP >= 5.4.0. For previous versions of PHP, use a variable to store the array before referencing it:
$bits = explode('/', $first);
echo 'http://myothersite.com/' . $bits[0];
From the manual:
As of PHP 5.4 it is possible to array dereference the result of a function or method call directly. Before it was only possible using a temporary variable.
Example output:
http://myothersite.com/whatIwant
http://myothersite.com/whatIwant2
http://myothersite.com/whatIwant3
This function should do the job.
<?php
function EditLink($link)
{
$link = explode("/",$link);
return $link[4];
}
$new_link = "http://myothersite.com/".EditLink("http://mysite1.com/test/whatIwant/Idontwantthis")."";
echo $new_link;
?>
Try this no regex:
$urls = array(
'http://mysite1.com/test/whatIwant3/Idontwantthiseither',
'http://mysite1.com/test/whatIwant/Idontwantthis',
'http://mysite1.com/test/whatIwant2/Istilldontwantthis'
);
$new_site = "http://myothersite.com/";
foreach ($urls as $url) {
$pathinfo = pathinfo($url);
$base = basename($pathinfo['dirname']);
$var = str_ireplace($url, $new_site . $base, $url);
echo $var . '<br>';
}
As of PHP 5.3:
$new_urls = array_map(function($url) { // anonymous function
global $new_site;
$pathinfo = pathinfo($url);
$base = basename($pathinfo['dirname']);
$var = str_ireplace($url, $new_site . $base, $url);
return $var;
}, $urls);
echo implode('<br>', $new_urls);
Sorry by my last answer, you was right, the order was correct.
Try this one with pre_replace, I beleave could solve the problem:
$var = "http://mysite1.com/test/whatIwant/Idontwantthis";
$var = preg_replace("/http\:\/\/mysite1.com\/([^\/]+)\/?.*/", "http://myothersite.com/$1", $var);
echo $var;

Checking if an index in a multidimensional array is an array

The code:
$row['text'] = 'http://t.co/iBSiZZD4 and http://t.co/1rG3oNmc and http://t.co/HGFjwqHI and http://t.co/8UldEAVt';
if(preg_match_all('|http:\/\/t.co\/.{1,8}|i',$row['text'],$matches)){
foreach($matches[0] as $value){
$headers = get_headers($value,1);
if(is_array($headers['Location'])){
$headers['Location'] = $headers['Location'][0];
}
$row['text'] = preg_replace('|http:\/\/t.co\/.{1,8}|i', '' . $headers['Location'] . '',$row['text']);
}
}
This is related to get_headers(). Sometimes get_headers($url,1) returns an array with a location index key like so: [Location]=>Array([0]=>url1 [1]=>url2). I basically want to make [Location] equal to [Location][0] if [Location][0] exists. However, the above code doesn't seem to accomplish that task. I've also tried array_key_exists() and isset() but neither solved the problem. Thoughts?
Don't try to replace on the fly. First get all the values, and then do the replace in one batch (using two arrays as the $search and $replace parameters).
<?php
$replace = array();
$row = array('text' => 'http://t.co/iBSiZZD4 and http://t.co/1rG3oNmc and http://t.co/HGFjwqHI and http://t.co/8UldEAVt');
if (preg_match_all('|http:\/\/t.co\/.{1,8}|i', $row['text'], $search)) {
foreach ($search[0] as $value) {
$headers = get_headers($value, 1);
if (is_array($headers['Location'])) {
$headers['Location'] = $headers['Location'][0];
}
$replace[] = "<a href='{$headers["Location"]}'>{$headers["Location"]}</a>";
}
$row['text'] = str_replace($search[0], $replace, $row['text']);
echo $row["text"];
}
P.S. - Next time, please tell us the context of your problem, tell us you "are making a service that resolves shortened URLs", don't let me figure that out from your code alone.

Yahoo Search API Problem

I am having problem with the yahoo search API, sometimes it works and sometimes don't why I am getting problem with that
I am using this URL
http://api.search.yahoo.com/WebSearchService/rss/webSearch.xml?appid=yahoosearchwebrss&query=originurlextension%3Apdf+$search&adult_ok=1&start=$start
The code is given below:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<? $search = $_GET["search"];
$replace = " "; $with = "+";
$search = str_replace($replace, $with, $search);
if ($rs =
$rss->get("http://api.search.yahoo.com/WebSearchService/rss/webSearch.xml?appid=yahoosearchwebrss&query=originurlextension%3Apdf+$search&adult_ok=1&start=$start")
)
{ }
// Go through the list powered by the search engine listed and get
// the data from each <item>
$colorCount="0";
foreach($rs['items'] as $item) { // Get the title of result
$title = $item['title']; // Get the description of the result
$description = $item['description']; // Get the link eg amazon.com
$urllink = $item['guid'];
if($colorCount%2==0) {
$color = ROW1_COLOR;
} else {
$color = ROW2_COLOR;
}
include "resulttemplate.php"; $colorCount++;
echo "\n";
}
?>
Sometimes it gives results and sometimes don't. I get this error usually
Warning: Invalid argument supplied for foreach() in /home4/thesisth/public_html/pdfsearchmachine/classes/rss.php on line 14
Can anyone help..
The error Warning: Invalid argument supplied for foreach() in /home4/thesisth/public_html/pdfsearchmachine/classes/rss.php on line 14 means the foreach construct did not receive an iterable (usually an array). Which in your case would mean the $rs['items'] is empty... maybe the search returned no results?
I would recommended adding some checks to the results of $rss->get("...") first, and also having an action for when the request fails or returns no results:
<?php
$search = isset($_GET["search"]) ? $_GET["search"] : "default search term";
$start = "something here"; // This was left out of your original code
$colorCount = "0";
$replace = " ";
$with = "+";
$search = str_replace($replace, $with, $search);
$rs = $rss->get("http://api.search.yahoo.com/WebSearchService/rss/webSearch.xml?appid=yahoosearchwebrss&query=originurlextension%3Apdf+$search&adult_ok=1&start=$start");
if (isset($rs) && isset($rs['items'])) {
foreach ($rs['items'] as $item) {
$title = $item['title']; // Get the title of the result
$description = $item['description']; // Get the description of the result
$urllink = $item['guid']; // Get the link eg amazon.com
$color = ($colorCount % 2) ? ROW2_COLOR : ROW1_COLOR;
include "resulttemplate.php";
echo "\n";
$colorCount++;
}
}
else {
echo "Could not find any results for your search '$search'";
}
Other changes:
$start was not declared before your $rss->get("...") call
compounded the $color if/else clause into a ternary operation with fewer comparisons
I wasn't sure what the purpose of the if ($rs = $rss->get("...")) { } was, so I removed it.
I would also recommend using require instead of include as it will cause a fatal error if resulttemplate.php doesn't exist, which in my opinion is a better way to detect bugs than PHP Warnings which will continue execution. However I don't know you whole situation so it might not be of great use.
Hope that helps!
Cheers

How do I remove specific URL from user input?

I want remove some URL from user input.
Example user input
$input = 'http://www.yahoo.com/';
$input = 'http://yahoo.com/';
$input = 'www.yahoo.com';
$input = 'yahoo.com';
$input = 'http://answers.yahoo.com/question/index;_ylt=AhiI2Ax0jmujpU01wK7W4cLj1KIX;_ylv=3?qid=20110224130854AA9LGdy';
$input = 'yahoo';
$input = 'http://yahoo.com';
$input = 'I love http://yahoo.com';
output I love
Any domain with yahoo.com I want remove the output or return empty result. Maybe more than one domain. Let me know.
Try something like this:
$domains = array('yahoo.com', 'other-domain.org');
$domainsrgx = implode('|', array_map('preg_quote', $domains));
$filtered_userinput = preg_replace('#(^|\s+)(https?://)?([^/\s]*\.)?('.$domainsrgx.')(/[^\s]*)?(?=(\s|$))#is', '', $userinput);
This should remove everything from your example.
$data=str_replace('yahoo.com','',$data);
you can use an array to replace\remove multiple domains
$remove=array('yahoo.com','google.com');
$data=str_replace($remove,'',$data);
Ok. You can do
$rows = split("[\n|\r]", $input);
$output = "";
foreach($rows as $row){
if(strpos($row,"yahoo.com")){
continue;
}else{
$output = $row."\n";
}
}
I hope I'm not missing anything.

Categories