如何将 PHP 输出实现到带有键数字的数组

脚本的输出是:“杰出的 1...杰出的 2...杰出的 3...”


例如,如何仅输出数组的第二个位置,以便可以单独输出结果?


像这样: $out[1]


<?php

$html = '

    <div class="page-wrapper">

        <section class="page single-review" itemtype="http://schema.org/Review" itemscope="" itemprop="review">

            <article class="review clearfix">

                <div class="review-content">

                    <div class="review-text" itemprop="reviewBody">

                    Outstanding 1... 

                    </div>

                    <div class="review-text" itemprop="reviewBody">

                    Outstanding 2... 

                    </div>

                </div>

            </article>

        </section>

    </div>

    <div class="review-text" itemprop="reviewBody">

    Outstanding 3... 

    </div>

';


$dom = new DOMDocument;

$dom->loadHTML ($html);

$xpath = new DOMXPath ($dom);

foreach ($xpath->query (".//div[@class='review-text']") as $review)

{

    $out = $review->nodeValue;

    echo $out;

}


?>


森栏
浏览 153回答 2
2回答

慕妹3242003

有两种方法可以做到这一点。要么将整个查询结果添加到这样的数组中$arr = $xpath->query (".//div[@class='review-text']")然后调用它$arr[1]->nodeValue或者如果 HTML 很大,你真的可以通过这样做来节省内存&nbsp; &nbsp; $counter = 0;&nbsp; &nbsp; foreach ($xpath->query (".//div[@class='review-text']") as $review)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; if ($counter == 1) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $out = $review->nodeValue;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; echo $out;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; $counter++;&nbsp; &nbsp; }根据您的需要,您可以选择其中一个选项。此外,如果您需要运行其他代码,但在 中打印foreach,第二种方法也可以这样做。

四季花海

你应该尝试这样的事情<?php$html = '<div class="page-wrapper">&nbsp; &nbsp; <section class="page single-review" itemtype="http://schema.org/Review" itemscope="" itemprop="review">&nbsp; &nbsp; &nbsp; &nbsp; <article class="review clearfix">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <div class="review-content">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <div class="review-text" itemprop="reviewBody">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Outstanding 1...&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <div class="review-text" itemprop="reviewBody">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Outstanding 2...&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; &nbsp; </article>&nbsp; &nbsp; </section></div><div class="review-text" itemprop="reviewBody">&nbsp; &nbsp; Outstanding 3...</div>';$dom = new DOMDocument;$dom->loadHTML ($html);$xpath = new DOMXPath ($dom);$reviews = $xpath->query (".//div[@class='review-text']");echo $reviews[1]->nodeValue; // Outstanding 2...关键是将所有评论存储在一个数组中,然后从数组中回显您想要的评论。
打开App,查看更多内容
随时随地看视频慕课网APP