How to avoid 'on a non-object in ***' error - php

I am using simple_html_dom like this
$html = new \simple_html_dom();
$html->load_file($url);
$html->find('a')
then sometims this error happens
Fatal error: Call to a member function find() on a non-object in /src/Acme/TopBundle/Command/simple_html_dom.php on line 1146
its OK. I think,it might happen that load_file fails to get contents of url;
but,I want to pass throw this error and continue process.
so I changed the script like this .
$html = new \simple_html_dom();
$html->load_file($url);
if (!$html){
return null;
}
$html->find('a')
but it still returns error and stop.
how can I pass throw this error?

Use is_object:
$html = new \simple_html_dom();
$html->load_file($url);
if (!is_object($html){
return null;
}
$html->find('a')

You can also do a defined check and use the gettype.
<?php
require('simple_html_dom.php');
$html = new \simple_html_dom();
$html->load_file('http://www.bensoft.com/');
if (defined($html) && gettype($html) == 'object') {
$html->find('a');
}
?>

Related

Catchable fatal error Object of class DOMDocument could not be converted to string

I am lost with this error:
Catchable fatal error Object of class DOMDocument could not be converted to string
This is my PHP code:
<?php
require_once('includes/mysqlConnect.php');
require_once('includes/utility.php');
//calling utility
$utility = new Utility();
//Creating a connection
$connection= new mySQL();
$connection->connect();
$getContent= file_get_contents('http://www.example.com/');
//echo $getContent;
//create a new DOMDocument Object
$doc= new DOMDocument();
//load HTML into DOMDoc
libxml_use_internal_errors(true);
$doc->loadHTML($getContent);
$utility->removeElementsByTagName('script', $doc);
$utility->removeElementsByTagName('style', $doc);
$utility->removeElementsByTagName('link', $doc);
echo $doc->saveHTML();
//Insert HTMl to DB
try
{
$result=$connection->db_query("CALL finalaggregator.insert_html('$doc')");
if ($result==0){
echo "<span style='color:red;'>Error! Data Saving Processes Unsuccessful</span>";
}
else {
echo "<span style='color:green;'>Data Successfully Saved!</span>";
}
}
catch (Exception $e){
echo "<span color='color:red;'>Error in Storing Data! Please Check Store Procedure.</span>";
}
?>
But always end up with showing
DOM Document could not be converted to string on line 29
I want to store the the value of $doc into a database.
When I am trying to to call the stored procedure from Mysql:
call finalaggregator.insert_html("<p>Testing123</p>");
it is working fine.
Please help me. I am new to php.
My stored procedure is as follow:
CREATE DEFINER=`root`#`localhost` PROCEDURE `insert_html`( IN HTML LONGTEXT)
BEGIN
INSERT INTO finalaggregator.site_html (html) VALUES(HTML);
END
You cannot simply use the instance of DOMDocument as a string in your query. You have to explicitly convert it to an HTML string first:
$html = $doc->saveHTML();
$result = $connection->db_query("CALL finalaggregator.insert_html('$html')");

weird html parser error Call to a member function find()

I have this error when parsing html
my code is like this
$html = new \simple_html_dom();
$html->load_file($url);
$type = gettype($html);
$this->output->writeln("check point1:" . $type); // it says 'object'
$class = get_class($html);
$this->output->writeln("check point2:" . $class); // it says 'simple_html_dom'
foreach($html->find('a') as $element){
//do something here.
}
then this code shows this error sometims.
PHP Fatal error: Call to a member function find() on a non-object
error
even when error happens $html is correctly fetched (I check in two check points)
This error is similar to this article though, no slution is revealed.
Please help me

domDocument loadHTML getElementsByTagName on a non-object issue

Im new to PHP, so im a little stuck in this code ex.
if U look at this Link there is a table, im trying to get only that table out and I know its the first table and its comming on source code line 1065.
But i get this error
bool(false)
Fatal error: Call to a member function getElementsByTagName() on a non-object in /get.php on line 23
I have this code, hope someone can guide me. (line 23 is the $rows..line)
<?php
$pulje = '163532';
$url = "http://www.dbu.dk/turneringer_og_resultater/resultatsoegning/position.aspx?poolid=$pulje";
// enable user error handling
var_dump(libxml_use_internal_errors(true));
// parse the html into DOMDoc.
$dom = new domDocument();
$dom->recover = true;
$dom->strictErrorChecking = false;
$dom->loadHTML($url);
$tables = $dom->getElementsByTagName('table');
$rows = $tables->item(count($tables-1))->getElementsByTagName('tr');
$array = array();
foreach($rows as $row){
$cols = $row->getElementsByTagName('td');
echo $array[] = $cols;
}
?>
....UPDATE....
I updated the code frem loadHTML to loadHTMLFile and then i now get this error
bool(false) Catchable fatal error: Object of class DOMNodeList could not be converted to string in /get.php on line 28
Line 28 is the echo $array....
You should use DOMDocument::loadHTMLFile instead of DOMDocument::loadHTML
DOMDocument::loadHTML : Load HTML from a string
DOMDocument::loadHTMLFile : Load HTML from a file
http://php.net/manual/en/domdocument.loadhtml.php
http://php.net/manual/en/domdocument.loadhtmlfile.php

PHP: Error in Error Checking

if($xml->getElementsByTagName($elmnt) && $xml->getElementsByTagName($elmnt)->length > 0)
This line is intended to check for errors. All I want is to, instead of breaking the entire page, make a legible error message. It is included in a function designed to stop all related processes on failure and continue displaying the rest of the page if it doesn't work, since the page layout does not depend on whether or not this function succeeds.
Fatal error: Call to a member function getElementsByTagName() on a non-object in file.php on line 100
How do I actually check to make sure that the DOMDocument in question has the element without it throwing the error above? I've tried using just the first condition or the second condition.
var_dump($xml);
object(DOMDocument)#3 (1) {
["preserveWhitespace"]=>
bool(false)
}
If you use simplexml_load_file to load the file, it will either return with a successfull load or it will return false on failure. The error you are getting signifies that the variable $xml is not an object, which means that when you tried to load the xml file onto the variable, it didn't do it successfully.
If before you do the getElementsByTagName($elmnt) you make sure $xml is not false, you shouldn't get the error Fatal error: Call to a member function getElementsByTagName() on a non-object in file.php on line 100
if (file_exists('test.xml')) {
$xml = simplexml_load_file('test.xml');
if($xml){
print_r($xml);
}
} else {
exit('Failed to open test.xml.');
}
Your problem is that $xml is not an object, you have to check that first:
if ($xml && ($obj = $xml->getElementsByTagName($elmnt)) && $obj->length > 0) {
// you should be good as this point
}
You can also use !empty($xml) instead of just $xml if there is a possibility that $xml is undefined.

PHP DOMElement is Immutable. = 'No Modification Allowed Error'

I cannot understand why this fails. Does a DOMElement need to be part of a Document?
$domEl = new DOMElement("Item");
$domEl->setAttribute('Something','bla');
Throws exception
> Uncaught exception 'DOMException' with message 'No Modification Allowed Error';
I would have thought I could just create a DOMElement and it would be mutable.
From http://php.net/manual/en/domelement.construct.php
Creates a new DOMElement object. This object is read only. It may be appended to a document, but additional nodes may not be appended to this node until the node is associated with a document. To create a writeable node, use DOMDocument::createElement or DOMDocument::createElementNS.
I needed to pass one instance of \DOMElement to a function in order to add children elements, so I ended up with a code like this:
class FooBar
{
public function buildXml() : string
{
$doc = new \DOMDocument();
$doc->formatOutput = true;
$parentElement = $doc->createElement('parentElement');
$this->appendFields($parentElement);
$doc->appendChild($parentElement);
return $doc->saveXML();
}
protected function appendFields(\DOMElement $parentElement) : void
{
// This will throw "No Modification Allowed Error"
// $el = new \DOMElement('childElement');
// $el->appendChild(new \DOMCDATASection('someValue'));
// but these will work
$el = $parentElement->appendChild(new \DOMElement('childElement1'));
$el->appendChild(new \DOMCdataSection('someValue1'));
$el2 = $parentElement->appendChild(new \DOMElement('childElement2'));
$el2->setAttribute('foo', 'bar');
$el2->appendChild(new \DOMCdataSection('someValue2'));
}
}

Categories