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
My Answer:
To get multiple itemprop values with xPath and PHP inside a DIV for WordPress, you can use the following code:
php
$html = 'John Doe
Web Developer
johndoe@example.com';
$doc = new DOMDocument();
$doc->loadHTML($html);
$xpath = new DOMXPath($doc);
$name = $xpath->query('//div[@itemprop="name"]')->item(0)->nodeValue;
$jobTitle = $xpath->query('//div[@itemprop="jobTitle"]')->item(0)->nodeValue;
$email = $xpath->query('//div[@itemprop="email"]')->item(0)->nodeValue;
echo '' . $name . '
';
echo '' . $jobTitle . '
';
echo '' . $email . '';
?>
This code will output the values of the `name`, `jobTitle`, and `email` properties inside a `DIV` with the `itemscope` attribute set to `http://schema.org/Person`. You can modify the HTML string `$html` to include additional `itemprop` values as needed.
Rate this post
4 of 5 based on 1603 votesComments