JFourie JFourie - 1 year ago 138
PHP Question

Php xpath get only the head

I want to use xPath to get only the contents of the head element.

//some curl request
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
curl_close ($ch);

$DOM = new DOMDocument;
if (!$DOM->loadHTML('<?xml encoding="utf-8" ?>' . $result)) {
$errors = "";
foreach (libxml_get_errors() as $error) {
$errors .= $error->message . "<br/>";
print "libxml errors:<br>$errors";
$xpath = new DOMXPath($DOM);
$head = $xpath->query('//*["head"]')->item(0); // Any suggestions?

As stated in the title, I am using PHP to try and extract the contents of whatever is in head in curl. Any suggestions is welcome.

Answer Source

If your curl response is as expected and everything up until your XPath is good, then try:

$head = $xpath->query('/head/*');
foreach ($head as $headElement) {
    /* DO STUFF*/

You may also not need to add <?xml encoding="utf-8" ?> to the beginning of the result.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download