Access specific node (custom_field) simplexml - parsing

This XML file, which can be accessed here # http://afdclinics.com/persistentpresence/category/brentwood/lobby-1/feed/ - has a custom_fields node with 2 fields called custom-bgcolor, and custom-fontcolor. I have tried numerous ways to try, and access the data inside them with no luck.
I have been accessing other nodes with simplexml, but haven't been able to get the custom_fields working. Here is what I have so far.
$curl = curl_init();
curl_setopt ($curl, CURLOPT_URL,'http://afdclinics.com/persistentpresence/category/brentwood/lobby-1/feed/');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec ($curl);
if ($result === false) {
die('Error fetching data: ' . curl_error($curl));
}
curl_close ($curl);
//we can at this point echo the XML if you want
//echo $result;
//parse xml string into SimpleXML objects
$xml = simplexml_load_string($result);
if ($xml === false) {
die('Error parsing XML');
}
//now we can loop through the xml structure
foreach ($xml->channel->item as $item) {
//print $item->title; rss feed article title
//print $item->description; rss feed article description
//print $item->link; rss feed article link
//print $item->pubDate; rss feed article publish date
print $item->children('content', true); //rss feed article content
// here is where is would like to print the custom values
print $item->custom_fields->custom-bgcolor; // this line doesn't seem to work
//gets img url's and appends them to offline manifest file
$imgUrl = array();
$doc2 = new DOMDocument();
$doc2->loadHTML($item->children('content', true));
$imgUrl = simplexml_import_dom($doc2);
$images = $imgUrl->xpath('//img');
foreach ($images as $img) {
$imgUrl = $img['src'] . "\r\n";
print $imgUrl; //rss feed image url's
$i++;
}

Related

TCPDF how do I create several pdf's without opening a browser

I need to create like 350 pdf's at once. Now the browser opens a window for each pdf. I takes longer to open all the 350 windows than to create the pdf's. How do I create and save the pdf's without opening a browser windows? (In my pdf I use Header, body and footer all with variables)
Now I do a loop on php_page_1 which opens the pdf create file.
$sql = "SELECT id FROM shipping_id WHERE datum BETWEEN $date_range AND acc_id=$acc_id;";
$STH = $dbo->prepare( $sql );
$STH->execute();
$contains_files = 0;
$client_id='';
while ( $row = $STH->fetch( PDO::FETCH_ASSOC ) ) {
$contains_files++;
$link = "vb_print_1_no_screen.php?id=" . $row[ 'id' ] . "&nr=".$contains_files;
echo '<script>window.open("https://' . $website_admin . $link . '");</script>';
}
You can use curl to make the request to the URL instead of opening it directly in the browser or you can just include the file that generates the PDF. Try this code
$sql = "SELECT id FROM shipping_id WHERE datum BETWEEN $date_range AND acc_id=$acc_id;";
$STH = $dbo->prepare( $sql );
$STH->execute();
$contains_files = 0;
$client_id='';
while ( $row = $STH->fetch( PDO::FETCH_ASSOC ) ) {
$contains_files++;
$link = "vb_print_1_no_screen.php?id=" . $row[ 'id' ] . "&nr=".$contains_files;
// echo '<script>window.open("https://' . $website_admin . $link . '");</script>';
// method 1 using curl
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $website_admin . $link);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$return = curl_exec($ch);
curl_close($ch);
// method 2 include pdf generator script
$_GET['id'] = $row['id'];
$_GET['nr'] = $contains_files;
include "vb_print_1_no_screen.php";
}
Kindly make sure to use just one method.

Google Translate in Flash (SWF) Action Script

We tried to code Google Translate in action script for Flash Professional CS6, but it does not function .
Can anyone help ?
The code does not return the trasnlated result .
The Code :
private function translate(e)
{
var result_lv:LoadVars = new LoadVars();
result_lv.onLoad = function () {
var str:String = unescape(this);
var txtContent;
var translatedText:String = str.split('":"')[1].split('"}, ')[0];
if(translatedText != undefined)
txtContent.text = translatedText.split('r').join('n').split('"').join("'");
return txtContent.text;
}
var lorem_lv:LoadVars = new LoadVars();
var from:String = "fa";
var to:String = "en"
lorem_lv.v = "1.0";
lorem_lv.format = "text";
lorem_lv.q = e;
lorem_lv.langpair = from + "|" + to;
lorem_lv.sendAndLoad(" http://ajax.googleapis.com/ajax/services/language/translate ", result_lv, "GET");
}
Code Explained :
Sample
LoadVars.sendAndLoad( )
Method Code Explained :
https://flylib.com/books/en/4.13.1.377/1/
================================================
Edit 1:
I edited my code :
I added the return code to the main function , so the main function has output .
but still the function does not return any transalted content .
The improved code :
private function translate(e)
{
var result_lv:LoadVars = new LoadVars();
var txtContent;
result_lv.onLoad = function () {
var str:String = unescape(this);
var translatedText:String = str.split('":"')[1].split('"}, ')[0];
if(translatedText != undefined)
txtContent.text = translatedText.split('r').join('n').split('"').join("'");
return txtContent.text;
}
var lorem_lv:LoadVars = new LoadVars();
var from:String = "fa";
var to:String = "en"
lorem_lv.v = "1.0";
lorem_lv.format = "text";
lorem_lv.q = e;
lorem_lv.langpair = from + "|" + to;
lorem_lv.sendAndLoad(" http://ajax.googleapis.com/ajax/services/language/translate ", result_lv, "GET");
return txtContent.text;
}
================================================
Edit 2:
We have found a working PHP function that return the translated result properly :
https://github.com/statickidz/php-google-translate-free/blob/1.1.1/src/GoogleTranslate.php
Now we are trying to load the PHP function result in the Action Script 2 for Adobe Flash Professional CS6.
here is some explanation about how this is possible :
Flash calling a PHP function
================================================
Edit 3:
A Good and Complete Book about PHP for Flash :
Foundation PHP for Flash 1st Edition :
https://www.amazon.com/Foundation-PHP-Flash-Steve-Webster/dp/1903450160
================================================
Edit 4:
Some Other Good and Complete Books about PHP for Flash :
Foundation PHP 5 for Flash 1st Edition :
https://www.amazon.com/Foundation-PHP-Flash-David-Powers/dp/B0096EPX7Q
Advanced PHP for Flash 1st ed. Edition :
https://www.amazon.com/Advanced-PHP-Flash-Steve-Webster/dp/1590591879
================================================
Edit 5:
We have rewritten the action script function that now use the PHP GoogleTranslate function .
See the answers below .
But it does not return the Translated result .
Please can someone help ?
Thanks
In the PHP-script that you've mentioned in comments, authors used the link https://translate.google.com/translate_a/single?... with some client authenticaton data like iid and also set User-Agent to Android phone:
curl_setopt($ch, CURLOPT_USERAGENT, 'AndroidTranslate/5.3.0.RC02.130475354-53000263 5.1 phone TRANSLATE_OPM5_TEST_1');
I think this script is trying to masquerade request like it was sent from Android Google Translate App.
But in your AcrionScript code you are using another URL:
lorem_lv.sendAndLoad(" http://ajax.googleapis.com/ajax/services/language/translate ", result_lv, "GET");
This simple-HTTP Google Translate API v1 is very old and already not available.
You can check it yourself by following this link - it's responds 404.
Here is the code that we have written :
Our function is written using the sample code on the below address :
Easy way to bring a php variable on flash with AS2
but it does not return the translated result . when I set the return String value to e variable the function work . but when I set the return to $output variable it does not function .
Action Script 2 Code :
function googletranslate(e:String):String
{
/*LoadVars send example*/
// init LoadVars Object
var lv:LoadVars = new LoadVars();
// set Variables
lv.sVar1 = "fa";
lv.sVar2 = "en";
lv.sVar3 = e;
// define onLoad Callback
lv.onLoad = onLoadCallBack;
// send and load variables
lv.sendAndLoad("google-translate-result.php?", lv, "POST");
var $output;
// onLoad Callback
function onLoadCallBack(succes)
{
// if succes
if(succes)
{
// trace variables
$output = this.lVarresult;
}
else
{
// loading failed
$output = "Loading Error!!";
}
}
return $output;
}
=============================================================
Edit :
The PHP (google-translate-result.php) Code is changed :
$_POST changed to $_GET and now the result php code is working itself through using this url :
Server_URL/google-translate-result.php?sVar1=fa&sVar2=en&sVar3=%DA%A9%D8%AA%D8%A7%D8%A8%20%D8%AA%D8%B3%D8%AA
but still the ActionScript does not return the Translated Result .
=============================================================
PHP Code (google-translate-result.php) :
<?php
require_once('GoogleTranslate.php');
// get variables
$var1 = $_GET['sVar1'];
$var2 = $_GET['sVar2'];
$var3 = $_GET['sVar3'];
$result = GoogleTranslate::translate($var1,$var2,$var3);
// send variables
echo "&lVarresult=$result&";
PHP Code (GoogleTranslate.php) :
<?php
/**
* GoogleTranslate.class.php
*
* Class to talk with Google Translator for free.
*
* #package PHP Google Translate Free;
* #category Translation
* #author Adrián Barrio Andrés
* #author Paris N. Baltazar Salguero <sieg.sb#gmail.com>
* #copyright 2016 Adrián Barrio Andrés
* #license https://opensource.org/licenses/GPL-3.0 GNU General Public License 3.0
* #version 2.0
* #link https://statickidz.com/
*/
/**
* Main class GoogleTranslate
*
* #package GoogleTranslate
*
*/
class GoogleTranslate
{
/**
* Retrieves the translation of a text
*
* #param string $source
* Original language of the text on notation xx. For example: es, en, it, fr...
* #param string $target
* Language to which you want to translate the text in format xx. For example: es, en, it, fr...
* #param string $text
* Text that you want to translate
*
* #return string a simple string with the translation of the text in the target language
*/
public static function translate($source, $target, $text)
{
// Request translation
$response = self::requestTranslation($source, $target, $text);
// Get translation text
// $response = self::getStringBetween("onmouseout=\"this.style.backgroundColor='#fff'\">", "</span></div>", strval($response));
// Clean translation
$translation = self::getSentencesFromJSON($response);
return $translation;
}
/**
* Internal function to make the request to the translator service
*
* #internal
*
* #param string $source
* Original language taken from the 'translate' function
* #param string $target
* Target language taken from the ' translate' function
* #param string $text
* Text to translate taken from the 'translate' function
*
* #return object[] The response of the translation service in JSON format
*/
protected static function requestTranslation($source, $target, $text)
{
// Google translate URL
$url = "https://translate.google.com/translate_a/single?client=at&dt=t&dt=ld&dt=qca&dt=rm&dt=bd&dj=1&hl=es-ES&ie=UTF-8&oe=UTF-8&inputm=2&otf=2&iid=1dd3b944-fa62-4b55-b330-74909a99969e";
$fields = array(
'sl' => urlencode($source),
'tl' => urlencode($target),
'q' => urlencode($text)
);
// URL-ify the data for the POST
$fields_string = "";
foreach ($fields as $key => $value) {
$fields_string .= $key . '=' . $value . '&';
}
rtrim($fields_string, '&');
// Open connection
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_ENCODING, 'UTF-8');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_USERAGENT, 'AndroidTranslate/5.3.0.RC02.130475354-53000263 5.1 phone TRANSLATE_OPM5_TEST_1');
// Execute post
$result = curl_exec($ch);
// Close connection
curl_close($ch);
return $result;
}
/**
* Dump of the JSON's response in an array
*
* #param string $json
* The JSON object returned by the request function
*
* #return string A single string with the translation
*/
protected static function getSentencesFromJSON($json)
{
$sentencesArray = json_decode($json, true);
$sentences = "";
foreach ($sentencesArray["sentences"] as $s) {
$sentences .= isset($s["trans"]) ? $s["trans"] : '';
}
return $sentences;
}
}
According to the Comments of the previous answer Action Script 2 Code changed to:
function googletranslate(e:String):String
{
/*LoadVars send example*/
// init LoadVars Object
var lv:LoadVars = new LoadVars();
var result_lv:LoadVars = new LoadVars();
// set Variables
lv.sVar1 = "fa";
lv.sVar2 = "en";
lv.sVar3 = e;
// send and load variables
lv.sendAndLoad("google-translate-result.php?", result_lv, "POST");
return result_lv.lVarresult;
}

Using GET to retrieve Data from my Webpage

I'm trying to use an ESP8266 NodeMCU to retrieve data from a database on my web page to control a LED. I'm struggling with the code on both sides for the ESP8266 to ask for the data and the web page to return it. I have the web page and database built. Here is the relevant bit of the server side PHP file, which isn't working....
if(!empty($_GET['mode']) && !empty($_GET['brightness']))
{
$mode = $_GET['mode'];
$brightness = $_GET['brightness'];
$sql = "SELECT * FROM config ORDER BY id DESC LIMIT 1 (mode, brightness)
$result = $conn->query($sql);
SELECT fields FROM table ORDER BY id DESC LIMIT 1;
VALUES ('".$mode."', '".$brightness."')";
if ($conn->query($sql) === TRUE) {
echo "1" . $row["id"]."<br>";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
$conn->close();
<code>
and on the ESP8266 side....
getData = "?mode=" "&brightness=";
Link = "http://***.com/Feed.php" + getData;
http.begin(Link); //Specify request destination
int httpCode = http.GET();
String payload = http.getString();
Mode = payload.substring(0,3);
String Brightness = payload.substring (4,6);
Thanks in advance!
I changed my approach and got it working. Instead of trying to return data from the web page to the ESP8266 I displayed the data on a very simple page....
<?php
$con=mysqli_connect("localhost","*****","*****","*****");
if (mysqli_connect_errno()) { echo "Failed to connect to config: " . mysqli_connect_error(); }
$result = mysqli_query($con,"SELECT * FROM config ORDER BY id DESC LIMIT 1");
while ($row = $result->fetch_assoc()) {
$mode = $row[mode]; $brightness = $row[brightness]; $speed = $row[speed];
print $mode;
print $brightness;
print $speed;
}
?>
and then had the ESP download the entire page and parsed out the data using substring like so...
HTTPClient http; //Declare object of class HTTPClient
Link = "http://*****.com/*****.php";
http.begin(Link); //Specify request destination
int httpCode = http.GET(); //Send the request
String payload = http.getString(); //Get the response payload
Mode = payload.substring(156,158).toInt();
Speed = payload.substring(158,160).toInt();
Brightness = payload.substring(160,162).toInt();

How to correctly use oembed to pull thumbs from youtube

I show a lot of thumbs on my homepage from youtube videos. I was using this function below to grab the thumb from a youtube url which works fast but it doesn't work for url's in the shortned form like youtu.be/JSHDLSKL.
function get_youtube_screen_link( $url = '', $type = 'default', $echo = true ) {
if( empty( $url ) )
return false;
if( !isset( $type ) )
$type = '';
$url = esc_url( $url );
preg_match("|[\\?&]v=([^&#]*)|",$url,$vid_id);
if( !isset( $vid_id[1] ) )
return false;
$img_server_num = 'i'. rand(1,4);
switch( $type ) {
case 'large':
$img_link = "http://{$img_server_num}.ytimg.com/vi/{$vid_id[1]}/0.jpg";
break;
case 'first':
// Thumbnail of the first frame
$img_link = "http://{$img_server_num}.ytimg.com/vi/{$vid_id[1]}/1.jpg";
break;
case 'small':
// Thumbnail of a later frame(i'm not sure how they determine this)
$img_link = "http://{$img_server_num}.ytimg.com/vi/{$vid_id[1]}/2.jpg";
break;
case 'default':
case '':
default:
$img_link = "http://{$img_server_num}.ytimg.com/vi/{$vid_id[1]}/default.jpg";
break;
}
if( $echo )
echo $img_link;
else
return $img_link;
}
So I tried to use Oembed to get the thumbs instead which works for all variations of the youtube url but it retrieves the 480px/360px thumb which causes a lot of cropping to get it down to the 120px/90px size I use to display them. The other issue was it caused my page speed to increase by 4 seconds which Im guessing is a problem with the way I'm implementing it. Here's how I call the thumb inside a loop.
<?php
require_once(ABSPATH.'wp-includes/class-oembed.php');
$oembed= new WP_oEmbed;
$name = get_post_meta($post->ID,'video_code',true);
$url = $name;
//As noted in the comments below, you can auto-detect the video provider with the following
$provider = $oembed->discover($name);
//$provider = 'http://www.youtube.com/oembed';
$video = $oembed->fetch($provider, $url, array('width' => 300, 'height' => 175));
$thumb = $video->thumbnail_url; if ($thumb) { ?>
<img src="<?php echo $thumb; ?>" width="120px" height="90px" />
<?php } ?>
So how should I be doing this to maximize efficiency?
I came across this page from youtube explaining their oembed support, They mentioned that they output to json format so I made a function that gets the json data and then enables you to use it.
Feel free to ask if you need more help.
<?php
$youtube_url = 'http://youtu.be/oHg5SJYRHA0'; // url to youtube video
function getJson($youtube_url){
$baseurl = 'http://www.youtube.com/oembed?url='; // youtube oembed base url
$url = $baseurl . $youtube_url . '&format=json'; // combines the url with format json
$json = json_decode(file_get_contents($url)); // gets url and decodes the json
return $json;
}
$json = getJson($youtube_url);
// from this point on you have all your data placed in variables.
$provider_url = $json->{'provider_url'};
$thumbnail_url = $json->{'thumbnail_url'};
$title = $json->{'title'};
$html = $json->{'html'};
$author_name = $json->{'author_name'};
$height = $json->{'height'};
$thumbnail_width = $json->{'thumbnail_width'};
$thumbnail_height = $json->{'thumbnail_height'};
$width = $json->{'width'};
$version = $json->{'version'};
$author_url = $json->{'author_url'};
$provider_name = $json->{'provider_name'};
$type = $json->{'type'};
echo '<img src="'.$thumbnail_url.'" />'; // echo'ing out the thumbnail image
Ok I came up with a solution from pieces of other questions. First we need to get the id from any type of url youtube has using this function.
function getVideoId($url)
{
$parsedUrl = parse_url($url);
if ($parsedUrl === false)
return false;
if (!empty($parsedUrl['query']))
{
$query = array();
parse_str($parsedUrl['query'], $query);
if (!empty($query['v']))
return $query['v'];
}
if (strtolower($parsedUrl['host']) == 'youtu.be')
return trim($parsedUrl['path'], '/');
return false;
}
Now we can get use YouTube Data API to get the thumbnail from the video id. Looks like this.
<?php
$vid_id = getVideoId($video_code);
$json = json_decode(file_get_contents("http://gdata.youtube.com/feeds/api/videos/$vid_id?v=2&alt=jsonc"));
echo '<img src="' . $json->data->thumbnail->sqDefault . '" width="176" height="126">';
?>
The problem is that is causing an extra 2 seconds load time so I simply use the $vid_id and place it inside http://i3.ytimg.com/vi/<?php echo $vid_id; ?>/default.jpg which gets rid of the 2 seconds added by accessing the youtube api.

Problems decoding JSON data from Twitter API (THM oauth)

I am using tmhOAuth.php / class to login into twitter. I have been successful in logging in and sending a tweet.
When I go to use the friends.php script, I am having some problems inserting into my database. I do believe that my problem lies some where with the $paging variable in the code. Because it is looping only seven times. I am following 626 people so my $ids is 626 and then $paging is 7.
When I run the php in a web browser, I am only able to extract 7 of the followers (ie following user #626,following user 526,following user 426...) It seem to be echoing the last user on each page request. This due in part to requesting 100 user ids at a time, via the PAGESIZE constant. When I adjust the $paging with different number such as the number 626 I get {"errors":[{"code":17,"message":"No user matches for specified terms"}]}
Unfortunately, I suspect this is fairly simple php looping problem, but after the amount of time I have spent trying to crack this I can no longer think straight.
Thanks in advance.
define('PAGESIZE', 100);
require 'tmhOAuth.php';
require 'tmhUtilities.php';
if ($tmhOAuth->response['code'] == 200) {
$data = json_decode($tmhOAuth->response['response'], true);
$ids += $data['ids'];
$cursor = $data['next_cursor_str'];
} else {
echo $tmhOAuth->response['response'];
break;
}
endwhile;
// lookup users
$paging = ceil(count($ids) / PAGESIZE);
$users = array();
for ($i=0; $i < $paging ; $i++) {
$set = array_slice($ids, $i*PAGESIZE, PAGESIZE);
$tmhOAuth->request('GET', $tmhOAuth->url('1/users/lookup'), array(
'user_id' => implode(',', $set)
));
// check the rate limit
check_rate_limit($tmhOAuth->response);
if ($tmhOAuth->response['code'] == 200) {
$data = json_decode($tmhOAuth->response['response'], true);
if ($tmhOAuth->response['code'] == 200) {
$data = json_decode($tmhOAuth->response['response'], true);
$name = array();
foreach ($data as $val)
{
$name = $data[0]['screen_name'];
}
echo "this is the screen name " .$name. "\n";
$users += $data;
} else {
echo $tmhOAuth->response['response'];
break;
}
}
var_dump($users);
?>
The data I am trying to echo, then parse and insert into database is the standard twitter JSON data, so I won't include this in the message. Any help would be
Problem solved:
foreach ($data as $val)
{
$name = $val['screen_name'];
echo "this is the screen name " .$name. "\n";
$users[] = $name;
}

Resources