【问题标题】:target html class and fill with content DOMdocument目标 html 类并填充内容 DOMdocument
【发布时间】:2013-03-19 21:51:34
【问题描述】:

我的目标是用内容填充某个 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>

我可以通过单个类 'ma​​inPageContent' 轻松获取元素的 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(我假设是因为查询正在寻找完全匹配),例如 'ma​​inContent':

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

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

$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

谁能指出我正确的方向?

谢谢, J

【问题讨论】:

    标签: xpath domdocument


    【解决方案1】:

    放弃以上所有内容,只使用 phpquery 库。

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

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

    【讨论】:

      猜你喜欢
      • 2012-09-13
      • 2012-10-22
      • 1970-01-01
      • 2017-11-26
      • 1970-01-01
      • 2017-11-15
      • 2017-04-12
      • 2020-09-10
      • 2019-10-04
      相关资源
      最近更新 更多