简体   繁体   中英

XML Xpath using PHP

Here is my XML:

<div class="main">  
    <div class="workshoplist-main">
        <div class="toggler pointer">
            <i class="icon-chevron-down"></i> 
            <span id="rpt_0_lblSectionHeader_0">Wednesday, March 18, 2015 (10:00 AM - 11:00 AM)</span> 
            <p>Description of March info</p>
        </div>
    </div>
    <div class="workshoplist-main">
        <div class="toggler pointer">
            <i class="icon-chevron-down"></i> 
            <span id="rpt_0_lblSectionHeader_1">Thursday, April 16, 2015 (10:00 AM - 11:00 AM)</span> 
            <p>Description of April info</p>
        </div>
    </div>
    <div class="workshoplist-main">
        <div class="toggler pointer">
            <i class="icon-chevron-down"></i> 
            <span id="rpt_0_lblSectionHeader_2">Friday, March 19, 2015 (10:00 AM - 11:00 AM)</span> 
            <p>Description of March info</p>
        </div>
    </div>  
</div>  

I want to look for the word March in the span element that contains lblSectionHeader in the id .

The return value I would like is:

 Wednesday, March 18, 2015 (10:00 AM - 11:00 AM)
 Friday, March 19, 2015 (10:00 AM - 11:00 AM)

My code is:

xpath("//div[contains(@class,'workshoplist-main') and //span[contains(@id,'lblSectionHeader')][text()='March']]");

I am getting no results. If anyone could help, that would be great.

The following query works:

$html = <<<'EOF'
    ... Your HTML comes here ...
EOF;

$doc = new DOMDocument();
$doc->loadHTML($html);

$selector = new DOMXPath($doc);
$query = "//div[contains(@class,'workshoplist-main')]//span[contains(@id,'lblSectionHeader')][contains(text(), 'March')]";

foreach($selector->query($query) as $node) {
    // do something with that node
    var_dump($node);
}

You misused the and keyword in your query. If you want to select <span> tags below a <div> tag (regardless of the nesting level) then use //div//span , not //div and //span

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