Есть ли способ вернуть HTML в PHP-функцию? (без построения возвращаемого значения в виде строки)
У меня есть функция PHP, которую я использую для вывода стандартного блока HTML. В настоящее время он выглядит так:
php function TestBlockHTML ($replStr) < ?> ?>
Я хочу вернуть (а не эхо) HTML внутри функции. Есть ли способ сделать это, не создавая HTML (выше) в строке?
Вы можете использовать heredoc , который поддерживает переменную интерполяцию, делая ее довольно аккуратной:
function TestBlockHTML ($replStr) < return HTML; >
Обратите особое внимание на предупреждение в руководстве, хотя – закрывающая строка не должна содержать пробелов, поэтому нельзя отступать.
Да, есть: вы можете захватить echo текст, используя ob_start :
Это может быть отрывочное решение, и я был бы признателен, если кто-нибудь укажет, является ли это плохая идея, поскольку это не стандартное использование функций. Мне удалось получить HTML из PHP-функции без создания возвращаемого значения в виде строки со следующим:
function noStrings() < echo ''?>[Whatever HTML you want]
Используя этот метод, вы также можете определить переменные PHP внутри функции и вывести их из HTML.
Создайте файл шаблона и используйте механизм шаблона для чтения / обновления файла. Это повысит надежность вашего кода в будущем, а также отдельный дисплей из логики.
Пример использования Smarty :
Файл шаблона
function TestBlockHTML()< $smarty = new Smarty(); $smarty->assign('title', 'My Title'); $smarty->assign('string', $replStr); return $smarty->render('template.tpl'); >
Другой способ сделать это – использовать file_get_contents () и создать HTML-страницу шаблона
function YOURFUNCTIONNAME($url)
return html from a php function
Hi thank you for your help, I had to amend your code slightly by taking out the $ sign when calling the key inside the foreach. I also added an if statement for best practice reasons.
function machineJobs($jobs) $output = ""; foreach ($jobs as $job) if ( isset($job['id']) and isset($job['jobTitle']) and isset($job['jobStartDate']) and isset($job['jobDuration']) and isset($job['qty'])) $output . p">tr>"; $output . p">td>".$job['id']."td>"; $output . p">td>".$job['jobTitle']."td>"; $output . p">td>".$job['jobStartDate']."td>"; $output . p">td>".$job['jobDuration']."td>"; $output . p">td>".$job['qty']."td> tr>"; >> return $output; >
Alexandre Babeanu
Alexandre Babeanu
Posting to the forum is only allowed for members with active accounts.
Please sign in or sign up to post.
Treehouse
See Full Catalogue
Techdegree
Tracks
Courses
Best way to return html from php function?
I wouldn’t return any HTML. Simply return the error message from the function and then build the html in a more appropriate place. For example the inside the template.
moodh 2501
Read More
If you may at some point have number of errors, then do like this
This is in case you are not using object oriented way. And assuming that all errors are not fatal and caught in try <> catch () <> blocks.
Generally, I try my best not to echo out HTML via PHP. Why? Because if a designer needs to work on my code, I don’t want him/her worrying about what HTML my functions are spitting out.
Similar Question and Answer
Move the html code into a separate file, error.php. After that you just capture the output:
function errMsg() < ob_start(); include '/path/to/error.php'; return ob_get_clean(); >// . echo errMsg();
Federkun 34483
First off, I agree with the posts above. Don’t format, just have the function return the bare error message and if you need to format it appropriately where you want to display it.
Secondly, I always find that it is useful to be able to turn error and testing messages on and off quickly. As the majority of my code is object orientated and I might only want to have messages popping from an object at a time, I normally have something like this in my classes:
class userObject < public $history;// = historyObject; public $userName; public $userRelation; public $userCode; private $mySQLAccessData; private $isDebug=false; public function makeHistoryObject($KPI, $KPIType) < if($this->isDebug)userName.".
";> $this->history = new historyObject($this->userCode, $KPI, $KPIType); > >
I slip a private element in which I leave as false by default. If I need to debug or make changes, I set it to true and all my error/logging messages are neatly displayed on screen. I know that this isn’t directly answering your question, but I do find that it is so handy it might be worth it for you when you start. It certainly beats commenting out and then uncommenting potentially dozens of messages. You can leave these outputs in the object without worrying and have them displaying all the detail you need.
- Yes definitely, you have no flexibility with the way you are doing it.
- You should separate all of your HTML from your PHP ideally, at least functions — the only place it is remotely acceptable is within a view which uses PHP just to display the output of the functions.
- Pizza! Just kidding, but there can never be enough pizza!?
Take a look at the Zend framework http://framework.zend.com/manual/en/zend.application.quick-start.html they forward error messages which aren’t caught to an error handler, which then uses its own view to render the error.
1: You don’t need to, but you can if it’s done properly.
2: To do this, i recommend you to use the EOF in your PHP error func, it looks like this :
function errMsg() < $error = O crap! There was an error
EOF; >
More Answer
- How to use variables from another php file to include in a html page javascript function
- return back data from php to html
- PHP — Best Way to Construct Timeline Data From Sets of Beginning and Ending Timestamps
- How to take a value from html forms and operate a php function on it?
- Proper php syntax for html return function
- PHP function return value to html tag
- How to return any kind of data from PHP Script Page to HTML Page without using JQuery or AJAX?
- PHP Return from Function and Stop Processing
- What’s the best way to remove some divs (with selectors) from an html string using php?
- How to call php function from html select option onChange?
- PHP populate html select with array from function
- Best way to pass JSON from PHP controller to AngularJS controller?
- php return two values in loop from a function
- does using $.ajax slows down the website? what’s the best way to retrieve instant data from a php file
- How to pass a value in php function paramater from a smary html template file
- proper way of calling a function from a different file in PHP
- PHP have cURL return HTML as function return string instead of outputing to client
- What is the best way to fetch images from S3 in PHP or Javascript?
- Sum numbers return from a php function
- PHP call function from parent in child best practice
- editing html using javascript that calls php function that gets information from sql database.. complicated.
- PHP Curl does not return a values from url
- Best way to store html in a config file
- Is there a way to get PHP to render HTML semantically?
- HTML Tables not visible, from PHP code
- Running code in Javascript to make a PHP and HTML file run from an ONLOAD event
- Simplest way to convert all html links in a string using PHP
- Stripping Specific HTML & Content from a page with PHP for RSS
- Right way for embedding HTML into PHP
- php cURL log into jsp website and return HTML
- PHP mail function interrupting jquery .post return data
- php function to get image coloured with gradient from grayscale
- Trigger jQuery function from PHP response
- Accessing html table from PHP
- calling javascript function from php code function is not defined
- Calling a html control from php code
More answer with same ag
- Symfony 1.4 Tasks Cannot Access Classes
- RTL control byte
- Return value from php to ajax error
- magento collection of a model isnt loaded
- MongoDB: how to get document with specific propety deep inside the object structure?
- Model view controller: Sending regularly displayed information to the view from controller
- How to use laravel collection to get array of matched value from multidimensional array
- jtable single column/field in a table refresh
- POST request in swift posting nothing
- How can I send verification code in email instead of sms using authy?
- Force file download by extension type with PHP
- yii2 captcha validation not work
- How to dynamically update field without refresh and without cilling the server?
- Relative file paths in PHP header file
- yaml handlers for google app engine
- Use PDO exec(array()) with several operands
- More trouble with collecting form data to Google Sheets
- AngularJS: Receiving posted data while file uploading
- Overwrite form mapper field options
- Add variables together in a foreach statement based on an ID
- phpmyadmin error with mbstring func overload
- PHP Singleton pattern, fatal error when calling getter
- Bind data into my form in ZF2
- max defers and failures per hour (5/5 (100%)) allowed — No CPanel
- Creating a select menu from variables and arrays
- Eliminating DEPRECATED errors form the error_log in PHP
- Copy record from a table to another table + add own record
- Is it possible to track mac address of client with PHP code. If yes how and if no why?
- Can’t set a cookie in Chrome 5
- Mvc pattern: where should I place this php code?
- Allow just one PHPSESSID per user
- How to decode the Json Object in php — angularJs
- How to write a route in Laravel without the root folder
- cron job on specific time and date
- PHP Submit form & Image stored image filename in database
- Refresh div after cliking a link _blank
- php string manipulation received by url after installing facebook app
- how to prevent server to block execution on long time running script
- How to find new client?
- Using while loop to fetch details in Swift Mailer
- How to make customizable form using php jquery?
- Regular Expression php for removing some content in double brackets
- SimplePie multiple feed demonstration code doesn’t work. What should I use instead?
- PHP Multiple variable object properties
- Setup react/zmq on windows
- Dynamic title depending on page (DRUPAL 7)
- Custom domains for one site
- yii framework for php $this->redirect() function
- How to use prepared statement for updating table instead of unprepared form
- mysqli_real_escape_string working using post but not working on if inserting value by assigning value to another variable