<?php
class parsedictionary {
public function _process() {
$webpage="http://www.oppapers.com/essays/Computerized-World/160871?read_essay";
$doc=new DOMDocument();
$doc->loadHTML($webpage);
echo $doc;
}
}
$obj=new parsedictionary();
$obj->_process();
?>
I can't get the content of that page.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
<body>
<p>http://www.oppapers.com/essays/Computerized-World/160871?read_essay</p>
</body>
</html>
But i need to get the content of that page.
The DOMDocument class is obviously not a string; you can iterate it, perform operations on it, but it can't just be echoed. Check the documentation to see what you can do with it: http://www.php.net/domdocument
To get the page contents, you can either use file_get_contents or do echo $doc->saveHTML()
Edit: Didn't realize you had another problem in your code; you can just use this instead:
public function _process() {
return file_get_contents('http://www.oppapers.com/essays/Computerized-World/160871?read_essay');
}
<?php
$doc->saveHTML();
?>
Works like a charm.
Well the error is pretty clear in this case. The _process() method cannot convert from one data type to another, it is expecting String and your feeding it a DomDocument. Perhaps you should try to extract all the text out of the DomDocument first as a string and then send that to the _process() method.
Related
I have an extremely simple implementation that pulls in a test bit of XML and attempts to validate it using DOMDocument. In testing, it's able to get through the LoadHTML() call fine, but as soon as I try and run validate(), the browser hangs forever and doesn't load. Here's the code:
$content = '<?xml version="1.0" encoding="utf-8"?><mainElement></mainElement>';
$dom = new DOMDocument;
$dom->LoadHTML($content);
if (!$dom->validate()) {
echo 'fail';
} else {
echo 'success!';
}
It seems that if you want to validate content loaded with loadHTML, you need DOCTYPE declaration (without it, you get an infinitive loop). For example, following code works and prints fail
$content = "
<!DOCTYPE html>
<html>
<body>
Content of the document......
</body>
</html>
";
$dom = new DOMDocument();
$dom->loadHTML($content);
if (!$dom->validate()) {
echo 'fail';
} else {
echo 'success!';
}
For XML it's more tolerant (it works even you didn't declare dtd but it returns false). In your case, you might use loadXML method and your code will print fail.
Tested with php 7.0.13.
I usually use Smarty template engine, so i separate database quesries and other logic from HTML template files, then assign received in PHP variable into Smarty via their function $smarty->assign('variableName', 'variableValue'); then display correct template file with HTML markup, and then i can use within that template my assigned variables.
But how correctly it will be done with .php file tempaltes, without Smarty?
For example, i use that construction:
_handlers/Handler_Show.php
$arData = $db->getAll('SELECT .....');
include_once '_template/home.php';
_template/home.php
<!DOCTYPE html>
<html>
<head>
....
</head>
<body>
...
<?php foreach($arData as $item) { ?>
<h2><?=$item['title']?></h2>
<?php } ?>
...
</body>
</html>
It's work. But i heard that it's not the best idea to do that.
So is this approach correct? Or maybe there's other way to organize it?
Give me advice, pelase.
Including templates in such a manner like in your example is not best idea because of template code is executed in the same namespace in which it is included. In your case template has access to database connection and other variables which should be separated from view.
In order to avoid this you can create class Template:
Template.php
<?php
class Template
{
private $tplPath;
private $tplData = array();
public function __construct($tplPath)
{
$this->tplPath = $tplPath;
}
public function __set($varName, $value)
{
$this->tplData[$varName] = $value;
}
public function render()
{
extract($this->tplData);
ob_start();
require($this->tplPath);
return ob_get_clean();
}
}
_handlers/Handler_Show.php
<?php
// some code, including Template class file, connecting to db etc..
$tpl = new Template('_template/home.php');
$tpl->arData = $db->getAll('SELECT .....');
echo $tpl->render();
_template/home.php
<?php
<!DOCTYPE html>
<html>
<head>
....
</head>
<body>
...
<?php foreach($arData as $item): ?>
<h2><?=$item['title']?></h2>
<?php endforeach; ?>
...
</body>
</html>
As of now template hasn't access to global namespace. Of course it is still possible to use global keyword,
or access template object private data (using $this variable), but this is much better solution than
including templates directly.
You can look at existing template system source code, for example plates.
I am a PHP beginner and trying to write PHP classes that work with HTML and MySql.
I am facing the following problem,
I have created a class called DatabaseManager that contains the function get_value. This function simply returns a value. In another file, I am calling this function on a button click using java script. But the link doesn't seem to work between the two files....Can someone help me?
thank you.
Here's my file that contains the PHP class.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Untitled 1</title>
</head>
<body>
<?php
class DatabaseManager {
private $value=1;
public function get_value ()
{
return value;
}
}
/php>
</body>
</html>
and here's the other file that calls it.
<html>
<head>
<?php include("DatabaseManager.php"); ?>
<script type="text/javascript">
function connect()
{
<?php
$database_manager= new DatabaseManager;
echo "the value is" . $database_manager->get_value();
?>
}
</script>
</head>
<body>
<input type="button" value="Search " onclick="connect()">
</body>
</html>
The name of the file that contains the function get_value is DatabaseManager.php
DO Like this
In Databasemanager.php
<?php
class DatabaseManager {
private $value = 1;
public function get_value() {
return $this->value;
}
}
?>
In another PHP file
<html>
<head>
<?php include("Databasemanager.php"); ?>
<script type="text/javascript">
function connect()
{
<?php
$database_manager= new DatabaseManager;
echo "the value is" . $database_manager->get_value();
?>
}
</script>
</head>
<body>
<input type="button" value="Search " onclick="connect()">
</body>
</html>
A few things:
in DatabaseManager.php remove all HTML. You're including the file elsewhere, you don't need or want duplicated HTML tags.
Remove the # in your MySQL section. This suppresses any errors you are having.
Switch to PDO or MySQLi. They are safer (if used properly)
Your closing php tag is wrong in the database file. You have /php> it should be ?>
Your class does absolutely nothing as-is.
There are multiple things here that you're douing wrong.
You don't need the html code in the first example.
You close the php wrong /php> should generate an error, it should be ?>
When your instantiating your DatabaseManager class you've left out the parentheses which means that the constructor will never get called, this should also generate an error.
You're probably trying to use alert in javascript which in this case you're not doing.
It should look something like this instead:
<?php
class DatabaseManager {
private $value = 1;
function getValue() {
return $this->value;
}
}
?>
And in your html (still php, but the one containing the html-markup) file:
<html>
<head>
<script type="text/javascript">
function connect() {
alert("
<?php
include "nameofDBManagerClassFile.php"
$dbm = new DatabaseManager();
echo "the value is " . $dbm->getValue();
?>
");
}
</script>
</head>
<body>
</body>
</html>
It could also be that you think that the php-code that is inside of the javascript function will not be executed untill you call the JS function connect() this is not so. PHP code is executed on the server and thus will be called when a user requests that webpage, the javascript on the other hand is clientside and will be executed in the users browser. I highly recommend that you read up on both php and JavaScript.
You do it wrong way, to output something in your JavaScript function connect() make this :
function connect() {
alert("
<?php
$database_manager= new DatabaseManager;
echo "the value is" . $database_manager->get_value();
?>
");
}
because php code is executed apart from your on click event.
Actually it's unclear what you wish to get, but you misunderstand the basics.
[edited to clarify users question how to output something to the screen]
I think the easiest way is to use require i another file.
require('login.php');
function get_value()
{
return get_value;
}
I have several functions in a class that return saveHTML(). After I echo more than one function in the class saveHTML(), it repeats some of the HTML. I initially solved this by doing saveHTML($node) but that doesn't seem to be an option now.
I didn't know saveHTML($domnode) was only available in PHP 5.3.6 and I have no control over the server I uploaded the files to so now I have to make it compatible with PHP 5.2.
For simplicity's sake it and only to show my problem it looks similar to this:
<?php
class HTML
{
private $dom;
function __construct($dom)
{
$this->dom = $dom;
}
public function create_paragraph()
{
$p = $this->dom->createElement('p','Text 1.');
$this->dom->appendChild($p);
return $this->dom->saveHTML();
}
public function create_paragraph2()
{
$p = $this->dom->createElement('p','Text 2.');
$this->dom->appendChild($p);
return $this->dom->saveHTML();
}
}
$dom = new DOMDocument;
$html = new HTML($dom);
?>
<html>
<body>
<?php
echo $html->create_paragraph();
echo $html->create_paragraph2();
?>
</body>
</html>
Outputs:
<html>
<body>
<p>Text 1.</p>
<p>Text 1.</p><p>Text 2.</p>
</body>
I have an idea why it's happening but I have no idea how to not make it repeat without saveHTML($domnode). How can I make it work properly with PHP 5.2?
Here's an example of what I want to be able to do:
http://codepad.viper-7.com/o61DdJ
What I do, is just save the node as XML. There are a few differences in the syntax, but it's good enough for most uses:
return $dom->saveXml($node);
You have return $this->dom->saveHTML(); twice in your class ( as far as I know you don't have to return it inside the class anywhere unless it is a private function.
If you take return $this->dom->saveHTML(); out of createparagraph() it will echo without returning. It's a DOM thing as far as I know but am new to this like you.
I have a PHP function that I'm using to output a standard block of HTML. It currently looks like this:
<?php function TestBlockHTML ($replStr) { ?>
<html>
<body><h1> <?php echo ($replStr) ?> </h1>
</html>
<?php } ?>
I want to return (rather than echo) the HTML inside the function. Is there any way to do this without building up the HTML (above) in a string?
You can use a heredoc, which supports variable interpolation, making it look fairly neat:
function TestBlockHTML ($replStr) {
return <<<HTML
<html>
<body><h1>{$replStr}</h1>
</body>
</html>
HTML;
}
Pay close attention to the warning in the manual though - the closing line must not contain any whitespace, so can't be indented.
Yes, there is: you can capture the echoed text using ob_start:
<?php function TestBlockHTML($replStr) {
ob_start(); ?>
<html>
<body><h1><?php echo($replStr) ?></h1>
</html>
<?php
return ob_get_clean();
} ?>
This may be a sketchy solution, and I'd appreciate anybody pointing out whether this is a bad idea, since it's not a standard use of functions. I've had some success getting HTML out of a PHP function without building the return value as a string with the following:
function noStrings() {
echo ''?>
<div>[Whatever HTML you want]</div>
<?php;
}
The just 'call' the function:
noStrings();
And it will output:
<div>[Whatever HTML you want]</div>
Using this method, you can also define PHP variables within the function and echo them out inside the HTML.
Create a template file and use a template engine to read/update the file. It will increase your code's maintainability in the future as well as separate display from logic.
An example using Smarty:
Template File
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head><title>{$title}</title></head>
<body>{$string}</body>
</html>
Code
function TestBlockHTML(){
$smarty = new Smarty();
$smarty->assign('title', 'My Title');
$smarty->assign('string', $replStr);
return $smarty->render('template.tpl');
}
Another way to do is is to use file_get_contents() and have a template HTML page
TEMPLATE PAGE
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head><title>$title</title></head>
<body>$content</body>
</html>
PHP Function
function YOURFUNCTIONNAME($url){
$html_string = file_get_contents($url);
return $html_string;
}
If you don't want to have to rely on a third party tool you can use this technique:
function TestBlockHTML($replStr){
$template =
'<html>
<body>
<h1>$str</h1>
</body>
</html>';
return strtr($template, array( '$str' => $replStr));
}
Or you can just use this:
<?
function TestHtml() {
# PUT HERE YOU PHP CODE
?>
<!-- HTML HERE -->
<? } ?>
to get content from this function , use this :
<?= file_get_contents(TestHtml()); ?>
That's it :)
Template File
<h1>{title}</h1>
<div>{username}</div>
PHP
if (($text = file_get_contents("file.html")) === false) {
$text = "";
}
$text = str_replace("{title}", "Title Here", $text);
$text = str_replace("{username}", "Username Here", $text);
then you can echo $text as string