简体   繁体   中英

xpath with HTML5 and PHP

I'm having a problem to use XPath with HTML5 in PHP. I'm using this code but it's not working with HTML5 elements, someone can help me?

$dom = new DomDocument;
$dom->loadHTMLFile($url);
$xpath = new DomXPath($dom);
$main = $xpath->query("//object");

foreach ($main as $i => $a) 
{
    echo $a->nodeValue;
}

I want to take the object element, this one:

<object type="application/x-shockwave-flash" data="" width="700" height="400">

I does perfectly work with any element :

test.html

<html>
  <body>
    <object type="application/x-shockwave-flash" data="" width="700" height="400"></object>
  </body>
</html>

test.php

$file = "test.html";
$dom = new DomDocument;
$dom->loadHTMLFile($file);
$xpath = new DomXPath($dom);
$elements = $xpath->query("/html/body/object");

if (!is_null($elements)) {
    foreach ($elements as $element) {
        print_r($element);
    }
}

even if you omit the </object> closing tag (which you shouldn't ).

HTML5 does not have to be an well formed xml.

So you cant gaurenteee that an xpath will work. To navigate the DOM you should use dom methods such as or if you have the likes of sizzle or jquery handy use the selector $("object"). 类的dom方法,或者如果您有类似izzizz或jquery之类的方法,请使用选择器$(“ object”)。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM