PHP & xPath Question



Answers

Just a wild guess, but echo $elements; is line 46, right? I believe the echo command expects something that is a string or convertible to a string, which $elements is not. Try removing that line.

Question

I'm using PHP and xPath to crawl into a website I own (just crawl the html not going into the server) but I get this error:

Catchable fatal error: Object of class DOMNodeList could not be converted to string in C:\wamp\www\crawler.php on line 46

I already tried echoing just that line to see what I was getting but I would just get the same error also I tried googling for the error but I, in the end, ended up in the php documentation and found out my example is exactly as the one in php documentation except I'm working with an HTML instead of a XML...so I have no idea what's wrong...here's my code...

<?php
$html = file_get_contents('http://miurl.com/mipagina#0');
// create document object model
$dom = new DOMDocument();
// load html into document object model
@$dom->loadHTML($html);
// create domxpath instance
$xPath = new DOMXPath($dom);
// get all elements with a particular id and then loop through and print the href attribute
$elements = $xPath->query("//*[@class='nombrecomplejo']");
if ($elements != null) {
    foreach ($elements as $e) {
      echo parse_str($e);
    } 
}                                                   
?>

Edit

Actually yes sorry that line was to test when I had commented other stuff...I deleted it here still have the error though.




Your code didn't format correctly so it would be hard for others to work on it.

However, the interactive tool here: http://www.bubasoft.net/ (XPath Builder) is very helpful when constructing XPath queries.




Object of class DOMElement could not be converted to string

$link is an object which can not be converted to string (some objects can).

To see which object it is, use var_dump($link);. I assume it's a DOMElementDocs, see the link for all properties and methods it has to offer, e.g.

echo $link->tagName;

or

echo $link->textContent;



CURL data in array

to take the cookie data and the location of a header, I use this code, hope this help.

You can try with any other information that the header can give you.

...
$result = curl_exec($ch);
curl_close($ch);

$var = explode("\n", $result);
$header = array();

foreach( $var as $row ) {
    if( strpos( strtolower($row), "set-cookie: " ) !== false ) {
        $header['set-cookie'] = str_ireplace("Set-Cookie: ", "", $row);
    } else if( strpos( strtolower($row), "location: " ) !== false ) {
        $header['location'] = str_ireplace("Location: ", "", $row);
    }
}

PS: I was mistaken, i believed that it was about the Header not the HTML content.




Related



Tags