目标html类并填充内容DOMdocument

时间:2013-03-19 21:51:35

标签: xpath domdocument

我的目标是用内容

填充某个std html类的html元素

这个答案有一个相当复杂的concat xpath查询: Using DOMDocument to extract from HTML document by class

这个类扩展将很好地获取和填充html: https://gist.github.com/j0shua/945507

这是我正在使用的示例html:

        <!-- actual content of the page box -->
    <div class="masterWidthSet mainContent">
        <div class="mainPageContent">
            <script type="text/javascript" src="/email_js.js"></script>

            <b>Contact us all at the same time...</b><br/>
            <div class="messageSent">Thank you for contacting us, we will get back to you as soon as possible.</div>
            <table class="contactForm">
                <tr><td class="title">Name</td><td class="description"><input type="text" id="sendName" class="text" placeholder="Your name..."></td></tr>

                <tr><td class="title">Number (optional)</td><td class="description"><input type="text" id="phoneNo" class="text"placeholder="Your number..."></td></tr>

                <tr><td class="title">Email</td><td class="description"><input type="text" id="email" class="text"placeholder="Your email..."></td></tr>

                <tr><td class="title">Message</td><td class="description"><textarea id="message" class="text"placeholder="Your message..."></textarea></td></tr>

                <tr><td></td><td class="description"><input type="button" class="submit" value="Send us you message..." onclick="sendMessage()"/><span class="description messageStatus" id="messageStatus"></span></td></tr>
            </table>
        </div>
    </div>

我可以使用单个类“ mainPageContent ”轻松获取元素的innHTML:

require_once WEBROOT_PRIVATE.'scripts/JSLikeHTMLElement.php';
$dom = new \DOMDocument();
$dom->registerNodeClass('DOMElement', 'JSLikeHTMLElement');
$dom->loadHTML( file_get_contents( $file['local_path'] ) );
$xpath = new \DOMXPath($dom);
$elem = $xpath->query('//*[@class="mainPageContent"]')->item(0);
echo $elem->innerHTML;

但是一旦我尝试使用多个类来定位一个元素,它就会返回null(我假设因为查询正在寻找完全匹配),例如' mainContent ':

$elem = $xpath->query('//*[@class="mainContent"]')->item(0);

所以我尝试使用顶部帖子中的concat查询,但我得到'调用成员函数项()':

$elem = $xpath->query("//*[contains(concat(' ', normalize-space(@class), ' '), ' mainContent ')")->item(0);

所以我试过这个:

$elem = $xpath->query('//*[class~="mainContent"]')->item(0);

问题是每次item(0)导致错误:

  

在非对象

上调用成员函数item()

这家伙说我尝试的方式应该有效.. Selecting a css class with xpath

有人能指出我正确的方向吗?

谢谢, Ĵ

1 个答案:

答案 0 :(得分:0)

废弃上述所有内容,只使用phpquery库。

就像jquery for php一样! bish bash bosh。

http://code.google.com/p/phpquery/