I have a class function that calls JSON from a URL. That function then sets a list of variables from the results of the JSON.
What I am attempting to do is call back one of those strings from inside of another file (index.html). I do not receive any errors back, however the results are blank.
I'm sure it's not due to the json command because it works properly when not placed inside of a class/function. To be sure I attempted to add $somestring4 = 'this is string 4' into the ClassFile.php and call it - it was also blank.
Here is my code...
ClassFile.php
<?php
class newClass {
Function newFunction(){
$jsonFetched = file_get_contents('http://url.com/file.json'); //<== MISSING SINGLE QUOTES ADDED FOR CODE-READABILITY...
$jsonQuery = json_decode($jsonFetched);
$someString1 = $jsonQuery->level1->level2->string1 ;
$someString2 = $jsonQuery->level1->level2->string2 ;
$someString3 = $jsonQuery->level1->level2->string3 ;
}
}
$foo = new newClass;
?>
Call from Index.html
<?php
include($sitePath . '/classes/ClassFile.php') ;
$refClass = new newClass();
$someString3 = $refClass->newFunction();
echo $someString3;
?>
Thanks for the help and sorry for the ignorance.
<?php
class newClass {
public $jsonFetched = '';
public $jsonQuery = '';
public $someString1 = '';
public $someString2 = '';
public $someString3 = '';
function newFunction(){
$jsonFetched = file_get_contents('http://url.com/file.json');
$jsonQuery = json_decode($jsonFetched);
$this->someString1 = $jsonQuery->level1->level2->string1 ;
$this->someString2 = $jsonQuery->level1->level2->string2 ;
$this->someString3 = $jsonQuery->level1->level2->string3 ;
}
}
?>
<?php
include($sitePath . '/classes/ClassFile.php') ;
$refClass = new newClass();
$refClass->newFunction();
echo $refClass->someString3;
?>
Related
I'm trying to request a REST API using PHP Unirest.
The printed error is the following:
Bad URL, colon is first character
And my code:
<?php
require __DIR__ . '/../vendor/autoload.php';
use Unirest\Request as UniRequest;
use CurlFile;
if (isset($_POST['primeiro'])) {
$where = $_POST["where"];
$equal = $_POST["equal"];
$resultado = new pedidos;
$valores = $resultado->LogIgualA($where, $equal);
}
class pedidos {
function LogIgualA($where, $equal) {
$wsURL = "localhost:8080/public";
try {
$valores = UniRequest::get($wsURL."/visual/json_log/where=".$where."/equal=".$equal, $headers, null);
} catch (Exception $e) {
echo $e->getMessage();
}
$valoresAux = $valores->body;
$valores = [];
foreach($valoresAux as $z){
$ID = $z->ID;
$DateConnection = $z->DateConnection;
$TimeToServe = $z->TimeToServe;
$ClientIP = $z->ClientIP;
$CacheCode = $z->CacheCode;
$Bytes = $z->Bytes;
$Method = $z->Method;
$RequestProtocol = $z->RequestProtocol;
$RequestIP = $z->RequestIP;
$RequestPort = $z->RequestPort;
$RequestFolder = $z->RequestFolder;
$Auth = $z->Auth;
$RouteLeft = $z->RouteLeft;
$RouteRight = $z->RouteRight;
$ContentType = $z->ContentType;
}
return $valores;
}
}
The "isset($_POST['primeiro']" is when I click the button in HTML so it calls the function in PHP.
I really don't know how to use this...
You need to prepend a protocol like https://.
There are other people having the same issue where prepending the protocol fixed this... https://github.com/Azure/doAzureParallel/issues/44
URL is not http: localhost:8080/public
Also check that there is no malicious input in your $_POST vars and maybe you need to use urlencode() on the fields containing appropriate characters.
I'm trying to create multiple .php files using php itself.
I want to put some code into a file; most of code is the same but only one or two variables that I wanted to be dynamic. I mean every file that I make are exactly like each other the only difference between theme is one variable.
My function is this:
function generate_corn_files()
{
$C = $GLOBALS['C'];
$db = $GLOBALS['db'];
//delete all contents of folder
RemoveDir($C->INCPATH.'cron/feed/', false);
$res = $db->query('SELECT id FROM category ');
while($cat = $db->fetch_object($res)) {
$id = $cat->id;
$open_output = <<<'PHP'
<?php
$outter_id = $id;
if($example = true){
echo 'test';
echo $C->INCPATH;
}
?>
PHP;
$fp=fopen($C->INCPATH.'cron/feed/filename_'.$id.'.php','w');
fwrite($fp, $open_output);
fclose($fp);
}
}
I tried to put content of file using heredoc but I want to $id in $outter_id = $id; be equal to $id = $cat->id;
it's a variable outside of heredoc I can't make it work inside of it !
Are there any other solutions to make it work ?
You aren't using HEREDOC syntax but rather NOWDOC syntax. If you use HEREDOC, all variables inside will be evaluated, so you will have to escape with \$ the variables you don't want evaluated.
$open_output = <<<PHP
<?php
\$outter_id = $id;
if(\$example = true){
echo 'test';
echo \$C->INCPATH;
}
?>
PHP;
Or, you can stick with NOWDOC, use a placeholder, and replace it afterwards.
$open_output = <<<'PHP'
<?php
$outter_id = %%%id%%%;
if($example = true){
echo 'test';
echo $C->INCPATH;
}
?>
PHP;
str_replace("%%%id%%%", $id, $open_output);
Maybe this could inspire you
function generate_corn_files()
{
$C = $GLOBALS['C'];
$db = $GLOBALS['db'];
//delete all contents of folder
RemoveDir($C->INCPATH.'cron/feed/', false);
$res = $db->query('SELECT id FROM category ');
while($cat = $db->fetch_object($res)) {
$id = $cat->id;
$open_output = <<<'PHP'
<?php
$outter_id = $id;
if($example = true){
echo 'test';
echo $C->INCPATH;
}
?>
PHP;
$php_var_name_pattern = '/\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)/';
$open_output = preg_replace_callback(
$php_var_name_pattern,
function($matches) {
if(isset($GLOBALS[$matches[1]])) {
if(is_string($GLOBALS[$matches[1]])) {
return '\''.$GLOBALS[$matches[1]].'\'';
} else {
return $GLOBALS[$matches[1]];
}
} else {
return $matches[0];
}
},
$open_output);
$fp=fopen($C->INCPATH.'cron/feed/filename_'.$id.'.php','w');
fwrite($fp, $open_output);
fclose($fp);
}
}
Here is the failure message I get in Terminal running 'phpunit tests':
1) StylistTest::test_find
null does not match expected type "object".
/Users/evanbutler/Desktop/hairSalonApp/tests/StylistTest.php:163
Here's my test method:
function test_find()
{
//Arrange
$name = "Stylist Jane";
$id = 1;
$name2 = "Stylist Bob";
$id2 = 2;
$test_stylist = new Stylist($name, $id);
$test_stylist->save();
$test_stylist2 = new Stylist($name2, $id2);
$test_stylist2->save();
//Act
$result = Stylist::find($test_stylist->getId());
//Assert
$this->assertEquals($test_stylist, $result);
}
And here's my method:
static function find($search_id)
{
$found_stylist = null;
$stylists = Stylist::getAll();
foreach($stylists as $stylist) {
$stylist_id = $stylist->getId();
if ($stylist_id == $search_id) {
$found_styist = $stylist;
}
}
return $found_stylist;
}
Here's my getAll method:
static function getAll()
{
$returned_stylists = $GLOBALS['DB']->query("SELECT * FROM stylists;");
$stylists = array();
foreach($returned_stylists as $stylist) {
$name = $stylist['name'];
$id = $stylist['id'];
$new_stylist = new Stylist($name, $id);
array_push($stylists, $new_stylist);
}
return $stylists;
}
If you'd like to see all my files here's the link to the git repository:
https://github.com/evanb2/hairSalonApp.git
I've been staring at this for way too long and I'm totally stumped.
Change
$found_styist = $stylist;
to
$found_stylist = $stylist;
You need a better IDE man. Simple static analysis could tell you about the unused variable.
I have a news article with internal links. In the RTE I see links like
http://www.yourdomain.com/?id=3
in the html text mode. The problem is that this link also appears on the frontend. RealURL should convert this link to something like
http://www.yourdomain.com/products/
The content of RTE is currently parsed like this
$parseObj = t3lib_div::makeInstance('t3lib_parsehtml_proc');
$txt = $parseObj->TS_links_rte($result['bodytext']);
$txt = $parseObj->TS_transform_rte($txt);
I read that I should use something like this
$pObj = t3lib_div::makeInstance('tslib_pibase');
$txt = $pObj->pi_RTEcssText($result['bodytext']);
but I don't know how can I access this function. I get
Fatal error: Call to a member function parseFunc() on a non-object in /home/myuser/www/home/typo3/sysext/cms/tslib/class.tslib_pibase.php on line 1384
What is the right way doing this? How can I access the function pi_RTEcssText? Do I have to use a class? Are there other ways doing it without a class?
EDIT:
I created a new template with TemplaVoila and defined lib.newscontent as TS object path.
TS Main Template
includeLibs.user_news = fileadmin/templates/php_scripts/news/class.news.php
lib.newscontent = USER_INT
lib.newscontent {
userFunc = user_news->main
userFunc.bodytext.parseFunc < lib.parseFunc_RTE
}
class.news.php
<?
class user_news {
var $cObj;
private $conf;
function main($content,$conf) {
$this->conf = $conf;
$this->setPreferences();
$content .= $this->aktuelleNews();
return $content;
}
private function aktuelleNews() {
$res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
'*', // SELECT ...
'tt_news', // FROM ...
'pid=22 AND deleted=0 AND hidden=0', // WHERE...
'', // GROUP BY...
'datetime DESC' // ORDER BY...
);
$i = 1;
$out_list = '<ul id="news">';
while ($data = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
$date = date("d.m.Y",$data['datetime']);
$out_list .= '<li>'.$date.': '.$data['title'].'</li>';
$out_detail.= $this->outputnewsdetail($data,$i);
$i++;
}
$out_list .= '</ul>';
return $out_list . $out_detail;
}
private function outputnewsdetail($result,$count){
$this->cObj->start($result, 'tt_news');
$bodytext = $this->cObj->stdWrap($result['bodytext'], $this->conf['bodytext']);
$bodytext = $this->cObj->parseFunc($bodytext,$GLOBALS['TSFE']->tmpl->setup['lib.']['parseFunc_RTE.']);
return $bodytext;
}
private function setPreferences() {
}
}
?>
localconf.php
include(PATH_site.'fileadmin/templates/php_scripts/news/class.news.php');
Remaining question
Why does the rendering part in the TS Main Template doesn't work? I used
$this->cObj->parseFunc($bodytext,$GLOBALS['TSFE']->tmpl->setup['lib.']['parseFunc_RTE.']);
to get my result.
I would prefer:
$txt = $this->cObj->stdWrap($result['bodytext'], $this->conf['bodytext.']);
You need in your main method: $this->conf = $conf;
In your TypoScript add the parseFunc to bodytext:
plugin.tx_yourplugin_pi1 {
bodytext.parseFunc < lib.parseFunc_RTE
}
The main idea is to use the usual parseFunc which is used by content elements. So you have the same rendering. Another benefit is, that your application is more flexible.
Just as a side note. It is worth to make a lokal cObj for that and hand over the complete data. So you are able to use alle fields in TypoScript. F.e. field = bodytext in your case.
# create lokal cObj - do not override the original data!
$cObj = t3lib_div::makeInstance('tslib_cObj');
foreach ($row = ...) {
# override data array with row. Every field in $row is now accesible via
# TypoScript field = fieldname
$cObj->start($row, $tableName);
$content .= $cObj->stdWrap($row['bodytext'], $this->conf['bodytext.']);
}
# TS Setup:
# in your case you could do somesthing like:
plugin.tx_yourplugin_pi1 {
bodytext.parseFunc < lib.parseFunc_RTE
bodytext.wrap = <div class="hide">|</div>
bodytext.prepend = TEXT
bodytext.prepend.field = bodytext
bodytext.prepend.stripHtml = 1
bodytext.prepend.crop = 30 | ... | 1
bodytext.prepend.wrap = <span title="|" onclick="showBodytext()">info</span>
}
If you need it in an user function try it like this:
function user_yourfunction($content,$conf) {
$result = *magic*
$cObj = t3lib_div::makeInstance('tslib_cObj');
$cObj->start($result, 'your table name');
return $cObj->stdWrap($result['bodytext'], $conf['bodytext.']);
}
In TypoScript:
includeLibs.something = media/scripts/example_callfunction.php
page.10 = TEXT
page.10 {
value = Hello World
postUserFunc = user_yourfunction
postUserFunc.bodytext.parseFunc < lib.parseFunc_RTE
}
ok so i have a php file that includes code for do a sql insert
myfile.php
include($somewhere.'/addleads.php');
addleads.php
require_once(MAIN_CLASS_PATH."common/class.Common.php");
require_once(MAIN_CLASS_PATH."modules/Leads/class.Leads.php");
$objcommon = new common();
$objLeads = new Leads();
$Errormsg = $objLeads->AddLBCleads($_REQUEST);
class.Leads.php
class Leads extends Common{
function Leads(){
$this->Common();
$this->Leadstype = "Leadstype";
$this->Leads = "Leads";
}
function AddLBCleads($objArray){
global $_REQUEST,$objSmarty,$global_config;
$objLeads = new Leads();
$objInsertArray['txtP_Ident'] = $objArray['selProperty'];
$objInsertArray['txtFirstName'] = $objArray['txtfirstname'];
$objInsertArray['txtLastName'] = $objArray['txtlastname'];
$objInsertArray['txtEmail'] = $objArray['txtEmail'];
$objInsertArray['txtPhone'] = $objArray['txtPhone'];
$objInsertArray['txtTypeId'] = $objArray['selleadtype'];
$objInsertArray['txtComments'] = $objArray['txtcomments'];
$StrEnterdate = date('Y-m-d H:i:s');
$objInsertArray['txtMoveDate'] = $StrMoveDate;
$objInsertArray['txtEntereddate'] = $StrEnterdate;
$current_id = $this->AddInfoToDB($objInsertArray,"txt",$this->LBCPrimary_leads);
How do i get $current_id from myfile.php, when i try to access it is unavailable
Just below this line:
class Leads extends Common{
Add:
public $current_id = null; // create a public accessible variable
And instead of:
$current_id = $this->AddInfoToDB($objInsertArray,"txt",$this->LBCPrimary_leads);
Use:
$this->current_id = $this->AddInfoToDB($objInsertArray,"txt",$this->LBCPrimary_leads);
Now you can get it like:
$objLeads = new Leads();
echo $objLeads->current_id;