dpict99695329 2015-10-25 18:56 采纳率: 100%
浏览 197

php / xpath:获取嵌套div中的内容

I have the following html code:

<div class='class1'> Content 1
<div class='class2'> Content 2
</div>
</div>

And I want to use xpath to only get the content between 'class1' and 'class2', aka just 'Content 1' by itself. This is what I have so far:

$classname = 'class1';
$results = $xpath->query("//*[@class='" . $classname . "']");
echo $results->item($x)->nodeValue;

But its returning back

Content 1 Content 2

Anyway to just get 'Content 1' by itself? Thanks!

  • 写回答

1条回答 默认 最新

  • dongyang2229 2015-10-25 20:35
    关注

    It is hard to know exactly what is going wrong with your code because we don't know what $x represents. The XPath you have is correct, but from you code I can't tell how you are printing your output. Below is a working example of what I think you are trying to achieve:

    PHP

    <?php
    
    $string = 
    <<<XML
        <div class='class1'> Content 1
            <div class='class2'> Content 2
            </div>
        </div>
    XML;
    
    $xml = new SimpleXMLElement($string);
    
    $results = $xml->xpath('//div[@class="class1"]');
    foreach($results as $result) {
        echo $result;
    } 
    
    ?>
    

    Output

    Content 1
    

    This creates a 'simple xml element' and then uses the XPath //div[@class="class1"] to look for your desired element. The $results variable returned is an array (which only holds one element), so I loop over it to print the desired output.

    评论

报告相同问题?

悬赏问题

  • ¥15 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line