I wrote the class Link which has a method shortTolong() this should return the real URL for a shortened url by returning the 'location' response header. i tested it and it works OK
here is the code
public function shortTolong()
{
$urlMatch = array();
$ch = curl_init();
$options = array
(
CURLOPT_URL=>$this->getUrl(),
CURLOPT_HEADER=>true,
CURLOPT_RETURNTRANSFER=>true,
CURLOPT_FOLLOWLOCATION=>false,
CURLOPT_NOBODY=>true);
curl_setopt_array($ch, $options);
$server_output = curl_exec($ch);
preg_match_all(LINK, $server_output,&$urlMatch,PREG_SET_ORDER);
if($urlMatch)
{
foreach($urlMatch as $set)
{
$extracted_url = $set[2].'://'.$set[3];
}
return $extracted_url;
}
else
{
return $this->getUrl();
}
}
the problem starts when i try to use this method on other file which uses FeedParser to get feed entries that contain this short urls i ned to analyze from some reason i get as a result the short url instead of the long one here is the code:
foreach($parser->getItems() as $item)
{
$idpreg = '/\d+/';
preg_match_all($idpreg, $item['ID'],$statusid);
$retweetid = ($statusid[0][1]);
$datetime = $item['PUBLISHED'];
$user = $item['AUTHOR']['NAME'];
preg_match_all(LINK, $item['TITLE'], &$linkMatch);
$final = $linkMatch[0][0];
//if($linkMatch[0][0])
echo '<p>';
$link = new Link($final);
echo $link->getUrl();
echo '<br>';
echo $link->shortTolong();
echo '<br>';
echo $user;
echo '<br>';
echo $retweetid;
echo '</p>';
}
from some reason i get the same result for getUrl() and shortTolong() and i know for certain this is an error.
any ideas why this is happening?
Thanks
Edit- I added an error notice to the method with curl_eror
i get this error message: "Protocol http not supported or disabled in libcurl"
as i said i tested this method from the and it's working fine as as stand alone in the same environment (no changes) i suspect it has something to do with FeedParser using curl too....
i think you should trim() the url and that should resolve the issue.
Related
I can't seem to find any code to display returned values from the call.
I am running the xml-lib from the software vendor at the following link
https://support.sippysoft.com/support/solutions/articles/3000013653-xml-rpc-api-sign-up-html-page-fresh-version-
<?php
include 'xmlrpc/xmlrpc.inc';
function listAccounts()
{
//$params = array(new xmlrpcval(array("i_account"=> new xmlrpcval('14719', "string")), 'struct'));
$msg = new xmlrpcmsg('listAccounts');
/* replace here URL and credentials to access to the API */
$cli = new xmlrpc_client('https://DOMAINHERE/xmlapi/xmlapi');
$cli->setSSLVerifyPeer(false);
$cli->setSSLVerifyHost(false);
$cli->setCredentials('USERNAME', 'PASSWORD', CURLAUTH_DIGEST);
$r = $cli->send($msg, 20);
if ($r->faultCode()) {
error_log("Fault. Code: " . $r->faultCode() . ", Reason: " . $r->faultString());
print_r ($r->faultString());
return false;
}
else
{
return $r->value();
// I need something here to write returned values to normal PHP variable
}
}
Ok thanks to the comment from halfer.
I managed to get the issue and digging through the code in the library I found a function that does the trick.
Thanks a million for your pointer it really helped.
I am new to php and xml and the learning curve is quite tall but thanks.
for someone else reference maybe in the future here is the corrected code with the last 2 lines that does the magic for me.
<?php
include 'xmlrpc/xmlrpc.inc';
// $params = array(new xmlrpcval(array("offset"=> new xmlrpcval("1", "int")
// ,"i_customer"=> new xmlrpcval("321", "int")
// ), 'struct'));
$params = array(new xmlrpcval(array("i_customer"=> new xmlrpcval("321", "int")
), 'struct'));
$msg = new xmlrpcmsg('listAccounts', $params);
/* replace here URL and credentials to access to the API */
$cli = new xmlrpc_client('DOMAIN');
$cli->setSSLVerifyPeer(false);
$cli->setdebug(0);
$r = $cli->send($msg, 20); /* 20 seconds timeout */
if ($r->faultCode()) {
error_log("Fault. Code: " . $r->faultCode() . ", Reason: " . $r->faultString());
echo $r->faultString();
}
// now lets decode the xml response..
$values=php_xmlrpc_decode($r->value());
var_dump ($values['accounts'][0][username]);
?>
I might be asking the wrong question here, but I cant seem to figure out where this is coming form. I am using both the HTTP Request2 and NET URL2 libraries in order to send some GET request to the Vuforia web services. This all works fine, but everytime I send a request, it also shows said request on screen.
GET d41d8cd98f00b204e9800998ecf8427e Mon, 09 Dec 2019 22:49:52 GMT /summary/ba2246f8cd29466899c69b8d05af09a1
The code that I use to get the above text appear on screen is as follows.
Main code:
<?php if(sizeof($items) > 0){
foreach($items as $item){
echo '<tr>';
echo'<td>'.$item['itemid'].'</td>';
echo'<td>'.$item['name'].'</td>';
echo'<td>'.$item['surname'].'</td>';
echo'<td>'.$item['phone'].'</td>';
$recos = $targetdata = json_decode(CheckVuforiaTarget("ba2246f8cd29466899c69b8d05af09a1"), true);
echo'<td>'.$recos['current_month_recos'].'</td>';
}
} else echo '<tr><td>Geen kandidaten</td></tr>';?>
Script holding the CheckVuforiaTarget function:
function CheckVuforiaTarget($vuforiaid){
$vuforiaTargetTracker = new TargetTracker($vuforiaid);
$response = $vuforiaTargetTracker->TargetTracker();
return ($response);
//print_r($vuforiaResult);
}
TargetTracker class:
<?php
require_once 'HTTP/Request2.php';
require_once 'SignatureBuilder.php';
// See the Vuforia Web Services Developer API Specification - https://developer.vuforia.com/resources/dev-guide/retrieving-target-cloud-database
// The DeleteTarget sample demonstrates how to delete a target from its Cloud Database using the target's target id.
// * note that targets cannot be 'Processing' and must be inactive to be deleted.
class TargetTracker{
//Server Keys
private $access_key = "...";
private $secret_key = "...";
private $url = "https://vws.vuforia.com";
private $requestPath = "/summary/";
private $request;
private $targetId = "";
public function __construct($targetId) {
$this->targetId = $targetId;
}
function TargetTracker(){
$this->requestPath = $this->requestPath . $this->targetId;
return $this->execTargetTracker();
}
public function execTargetTracker(){
$this->request = new HTTP_Request2();
$this->request->setMethod( HTTP_Request2::METHOD_GET );
$this->request->setConfig(array('ssl_verify_peer' => false));
$this->request->setURL( $this->url . $this->requestPath );
$this->setHeaders();
try {
$response = $this->request->send();
if (200 == $response->getStatus()) {
return $response->getBody();
} else {
//echo 'Unexpected HTTP status: ' . $response->getStatus() . ' ' .
// $response->getReasonPhrase(). ' ' . $response->getBody();
return $response->getBody();
}
} catch (HTTP_Request2_Exception $e) {
return $e->getMessage();
}
}
private function setHeaders(){
$sb = new SignatureBuilder();
$date = new DateTime("now", new DateTimeZone("GMT"));
// Define the Date field using the proper GMT format
$this->request->setHeader('Date', $date->format("D, d M Y H:i:s") . " GMT" );
// Generate the Auth field value by concatenating the public server access key w/ the private query signature for this request
$this->request->setHeader("Authorization" , "VWS " . $this->access_key . ":" . $sb->tmsSignature( $this->request , $this->secret_key ));
}
}
?>
Both HTTP/Request2.php(and everything it came with) and SignatureBuilder.php are both default scripts/classes I've downloaded from the internet without altering them.
Now with my basic understanding of PHP, i've tried to find anything related to an echo or whatever command would show this on screen, but I can't seem to find it.
Does someone have some pointers for me, so I can figure out the source?
Thanks in advance!
The code you provided has no echo/print output that would explain the message you see. The echo/print statement must be somewhere else.
I would like to be able to extract a title and description from Wikipedia using json. So... wikipedia isn't my problem, I'm new to json and would like to know how to use it. Now I know there are hundreds of tutorials, but I've been working for hours and it just doesn't display anything, heres my code:
<?php
$url="http://en.wikipedia.org/w/api.php?action=query&prop=extracts|info&exintro&titles=google&format=json&explaintext&redirects&inprop=url";
$json = file_get_contents($url);
$data = json_decode($json, TRUE);
$pageid = $data->query->pageids;
echo $data->query->pages->$pageid->title;
?>
Just so it easier to click:
http://en.wikipedia.org/w/api.php?action=query&prop=extracts|info&exintro&titles=google&format=json&explaintext&redirects&inprop=url&indexpageids
I know I've probably just done a tiny thing wrong, but its really bugging me, and the code... I'm used to using xml, and I have pretty much just made the switch, so can you explain it a bit for me and for future visitors, because I'm very confused... Anything you need that I haven't said, just comment it, im sure I can get it, and thanks, in advance!
$pageid was returning an array with one element. If you only want to get the fist one, you should do this:
$pageid = $data->query->pageids[0];
You were probably getting this warning:
Array to string conversion
Full code:
$url = 'http://en.wikipedia.org/w/api.php?action=query&prop=extracts|info&exintro&titles=google&format=json&explaintext&redirects&inprop=url&indexpageids';
$json = file_get_contents($url);
$data = json_decode($json);
$pageid = $data->query->pageids[0];
echo $data->query->pages->$pageid->title;
I'd do it like this. It supports there being multiple pages in the same call.
$url = "http://en.wikipedia.org/w/api.php?action=query&prop=extracts|info&exintro&titles=google&format=json&explaintext&redirects&inprop=url";
$json = file_get_contents($url);
$data = json_decode($json, TRUE);
$titles = array();
foreach ($data['query']['pages'] as $page) {
$titles[] = $page['title'];
}
var_dump($titles);
/* var_dump returns
array(1) {
[0]=>
string(6) "Google"
}
*/
Try this it will help you 💯%
This code is to extract title and description with the help of Wikipedia api from Wikipedia
<?php
$url = 'http://en.wikipedia.org/w/api.php?action=query&prop=extracts|info&exintro&titles=google&format=json&explaintext&redirects&inprop=url&indexpageids';
$json = file_get_contents($url);
$data = json_decode($json);
$pageid = $data->query->pageids[0];
$title = $data->query->pages->$pageid->title;
echo "<b>Title:</b> ".$title."<br>";
$string=$data->query->pages->$pageid->extract;
// to short the length of the string
$description = mb_strimwidth($string, 0, 322, '...');
// if you don't want to trim the text use this
/*
echo "<b>Description:</b> ".$string;
*/
echo "<b>Description:</b> ".$description;
?>
My php project is using the reddit JSON api to grab the title of the current page's submission.
Right now I am doing running some code every time the page is loaded and I'm running in to some problems, even though there is no real API limit.
I would like to store the title of the submission locally somehow. Can you recommend the best way to do this? The site is running on appfog. What would you recommend?
This is my current code:
<?php
/* settings */
$url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
$reddit_url = 'http://www.reddit.com/api/info.{format}?url='.$url;
$format = 'json'; //use XML if you'd like...JSON FTW!
$title = '';
/* action */
$content = get_url(str_replace('{format}',$format,$reddit_url)); //again, can be xml or json
if($content) {
if($format == 'json') {
$json = json_decode($content,true);
foreach($json['data']['children'] as $child) { // we want all children for this example
$title= $child['data']['title'];
}
}
}
/* output */
/* utility function: go get it! */
function get_url($url) {
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,1);
$content = curl_exec($ch);
curl_close($ch);
return $content;
}
?>
Thanks!
Introduction
Here is a modified version of your code
$url = "http://stackoverflow.com/";
$loader = new Loader();
$loader->parse($url);
printf("<h4>New List : %d</h4>", count($loader));
printf("<ul>");
foreach ( $loader as $content ) {
printf("<li>%s</li>", $content['title']);
}
printf("</ul>");
Output
New List : 7New podcast from Joel Spolsky and Jeff Atwood. Good site for example code/ Pyhtonstackoverflow.com has clearly the best Web code ever conceived in the history of the Internet and reddit should better start copying it.A reddit-like, OpenID using website for programmersGreat developer site. Get your questions answered and by someone who knows.Stack Overflow launched into publicStack Overflow, a programming Q & A site. & Reddit could learn a lot from their interface!
Simple Demo
The Problem
I see some things you want to achieve here namely
I would like to store the title of the submission locally somehow
Right now I am doing running some code every time the page is loaded
From what i understand you need is a simple cache copy of your data so that you don't have to load the url all the time.
Simple Solution
A simple cache system you can use is memcache ..
Example A
$url = "http://stackoverflow.com/";
// Start cache
$m = new Memcache();
$m->addserver("localhost");
$cache = $m->get(sha1($url));
if ($cache) {
// Use cache copy
$loader = $cache;
printf("<h2>Cache List: %d</h2>", count($loader));
} else {
// Start a new Loader
$loader = new Loader();
$loader->parse($url);
printf("<h2>New List : %d</h2>", count($loader));
$m->set(sha1($url), $loader);
}
// Oupput all listing
printf("<ul>");
foreach ( $loader as $content ) {
printf("<li>%s</li>", $content['title']);
}
printf("</ul>");
Example B
You can use Last Modification Date as the cache key as so that you would only save new copy only if the document is modified
$headers = get_headers(sprintf("http://www.reddit.com/api/info.json?url=%s",$url), true);
$time = strtotime($headers['Date']); // get last modification date
$cache = $m->get($time);
if ($cache) {
$loader = $cache;
}
Since your class implements JsonSerializable you can json encode your result and also store in a Database like MongoDB or MySQL
$data = json_encode($loader);
// Save to DB
Class Used
class Loader implements IteratorAggregate, Countable, JsonSerializable {
private $request = "http://www.reddit.com/api/info.json?url=%s";
private $data = array();
private $total;
function parse($url) {
$content = json_decode($this->getContent(sprintf($this->request, $url)), true);
$this->data = array_map(function ($v) {
return $v['data'];
}, $content['data']['children']);
$this->total = count($this->data);
}
public function getIterator() {
return new ArrayIterator($this->data);
}
public function count() {
return $this->total;
}
public function getType() {
return $this->type;
}
public function jsonSerialize() {
return $this->data;
}
function getContent($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 1);
$content = curl_exec($ch);
curl_close($ch);
return $content;
}
}
I'm not sure what your question is exactly but the first thing that pops is the following:
foreach($json['data']['children'] as $child) { // we want all children for this example
$title= $child['data']['title'];
}
Are you sure you want to overwrite $title? In effect, that will only hold the last $child title.
Now, to your question. I assume you're looking for some kind of mechanism to cache the contents of the requested URL so you don't have to re-issue the request every time, am I right? I don't have any experience with appFog, only with orchestra.io but I believe they have the same restrictions regarding writing to files, as in you can only write to temporary files.
My suggestion would be to cache the (processed) response in either:
APC shared memory with a short TTL
temporary files
database
You could use the hash of the URL + arguments as the lookup key, doing this check inside get_url() would mean you wouldn't need to change any other part of your code and it would only take ~3 LOC.
After this:
if($format == 'json') {
$json = json_decode($content,true);
foreach($json['data']['children'] as $child) { // we want all children for this example
$title = $child['data']['title'];
}
}
}`
Then store in a json file and dump it into your localfolder website path
$storeTitle = array('title'=>$title)
$fp = fopen('../pathToJsonFile/title.json'), 'w');
fwrite($fp, json_encode($storeTitle));
fclose($fp);
Then you can always call the json file next time and decode it and extract the title into a variable for use
i usually just store the data as is as a flat file, like so:
<?php
define('TEMP_DIR', 'temp/');
define('TEMP_AGE', 3600);
function getinfo($url) {
$temp = TEMP_DIR . urlencode($url) . '.json';
if(!file_exists($temp) OR time() - filemtime($temp) > TEMP_AGE) {
$info = "http://www.reddit.com/api/info.json?url=$url";
$json = file_get_contents($info);
file_put_contents($temp, $json);
}
else {
$json = file_get_contents($temp);
}
$json = json_decode($json, true);
$titles = array();
foreach($json['data']['children'] as $child) {
$titles[] = $child['data']['title'];
}
return $titles;
}
$test = getinfo('http://imgur.com/');
print_r($test);
PS.
i use file_get_contents to get the json data, you might have your own reasons to use curl.
also i don't check for format, cos clearly you prefer json.
I would like to add a video to a playlist using GData. So I have no problem creating the playlist, but I can't manage to add a video to it.
Here's what I do:
$playlist = $yt->newPlaylistListEntry();
$playlist->summary = $yt->newDescription()->setText("test");
$playlist->title = $yt->newTitle()->setText("test2");
$postLocation = 'http://gdata.youtube.com/feeds/api/users/default/playlists';
$yt->insertEntry($playlist, $postLocation);
$feedUrl = $playlist->getPlaylistVideoFeedUrl();
$videoEntryToAdd = $yt->getVideoEntry(..given id here..);
$newPlaylistListEntry = $yt->newPlaylistListEntry($videoEntryToAdd->getDOM());
$yt->insertEntry($newPlaylistListEntry, $feedUrl);
And I get the following error:
Notice: Trying to get property of non-object in C:...\library\Zend\Gdata\YouTube\PlaylistListEntry.php on line 296
Which is caused by this code:
$feedUrl = $playlist->getPlaylistVideoFeedUrl();
var_dump shows that the $feed_url is NULL. And it shows that $playlist is an object Zend_Gdata_YouTube_PlaylistListEntry, so I can't understand why it writes "property of non-object".
It seems like it is some kind of a bug in the API. So I've made a little workaround. It may seem ugly, but I had no other ideas.
function grab_dump($var)
{
ob_start();
var_dump($var);
return ob_get_clean();
}
function getPlayListLink($playlist) {
$test = grab_dump($playlist);
$test = strstr($test, "http://gdata.youtube.com/feeds/api/playlists/");
return strstr($test, "' countHint='0'", TRUE);
}
function addVideosToPlaylist($videos_arr, $playlistEntry, $yt) {
$feedUrl = getPlayListLink($playlistEntry);
foreach($videos_arr as $video)
{
$videoEntryToAdd = $yt->getVideoEntry($video);
$newPlaylistListEntry = $yt->newPlaylistListEntry($videoEntryToAdd->getDOM());
$yt->insertEntry($newPlaylistListEntry, $feedUrl);
}
}
And simply call it like that:
addVideosToPlaylist($vids_id, $playlist, $yt);