简体   繁体   中英

Scraping specific tag property in PHP using DOMDocument

I am trying to extract the content from 'meta' tag depending upon the 'property'. Like `

<meta name="keywords" content="9gag,fun,funny,lol,meme,GIF,wtf,omg,fail,video,cosplay,geeky,forever alone" />
<meta name="twitter:image" content="http://images-cdn.9gag.com/images/thumbnail-facebook/14198244_1420182794.8999_AmeJun_n.jpg" />
<meta property="og:title" content="I finished the manga last week, so I wanted to make my on &quot;What Naruto taught me&quot;" />
<meta property="og:site_name" content="9GAG" />
<meta property="og:url" content="http://9gag.com/gag/aGVqbvz" />

... ` so I want to get only those content having 'og'. Through a cURL request I have been able to get attributes.

$ch = curl("http://9gag.com/gag/aGVqbvz?ref=fsidebar");
$dom = new DOMDocument();
@$dom->loadHTML($ch);

//echo $ch;
$links = $dom->getElementsByTagName('meta');
//get no of tags or elements
echo $links->length;
echo '<pre>';
foreach ($links as $link) {
    echo $link->getAttribute("property");
    echo '<br>';
}

how can I get content specific to only particular property or name.

XPath is your friend here. An expression like //meta[starts-with(@property, "og")]/@content will grab the content attributes for all meta elements that have a property attribute whose value begins with "og".

Example:

$xpath = new DOMXPath($dom);
$query = '//meta[starts-with(@property, "og")]/@content';
foreach ($xpath->query($query) as $node) {
    echo $node->value, "\n";
}

Output:

I finished the manga last week, so I wanted to make my on "What Naruto taught me"
9GAG
http://9gag.com/gag/aGVqbvz

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