skip to Main Content

I have the following code

<div class="content"></div>
<div class="content">
 <h3 itemprop="name">Grab this text</h3><div itemprop="description">Grab this text too</div>
</div>

How can I grab both those text parts and place them inside variables?
I’m working in WordPress, building a plugin. There are multiple itemprops on the page that I don’t want, so I can’t select just those.

I’ve tried

$name = $xpath->query( '//div[@class="content"]//h3[@itemprop="name"]' );

But that doesn’t select the second part description and leaves me with an error when I try to echo it.

I think I might have to iterate through them after grabbing the main div, but I’m not sure how to do that, and I looked up a few other stacks that didn’t help.

Thanks

2

Answers


  1. Chosen as BEST ANSWER

    Thanks @Siebe, your answer partly helped, so I didn't accept the answer I wanted to post what the difference I found making it work.

    I got the name and description separate.

    //div[@class="content"]//@itemprop[.="name"]
    //div[@class="content"]//@itemprop[.="description"]
    

    Thanks for the idea of the .= that's what I was missing.


  2. If the filter of @itemprop inside div[@class="content"] is enough, use this:

    $name = $xpath->query( '//div[@class="content"]/*[@itemprop]' );
    

    If you are only interested in @itemprop with the value ‘name’ or ‘description’ use this:

    $name = $xpath->query( '//div[@class="content"]/*[@itemprop[.="name" or .="description"]]' );
    

    The * means any element, so it will find both h3 and div

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search