get an array of meta tags php

2019-07-27 11:40发布

问题:

How can I get all of the values from the <meta> named "tag" and echo them on the page?

this is the HTML im using:

<meta name="tag" content="plant"/>
<meta name="tag" content="leaf"/>
<meta name="tag" content="waterdroplet"/>
<meta name="tag" content="water"/>

PHP that im using:

$tags = array (get_meta_tags ( "http://s0ulp1xel.x10.mx/background-garage/?p=photo&photo=1"));
echo $tags;

The result is that it only echos the last <meta> named "tag".

回答1:

get_meta_tags returns an array, use print_r() to see it's structure, and loop through them to print them however you want:

foreach($tags as $tag){
  echo $tag."\n";
}

Edit: And you don't need to stick the restult of get_meta_tags in another array, then you just have an extra one for no reason.

explode(',',$meta['tags']);


回答2:

If your question is now how would I get comma-separated values as different tags?, you could do something like this:

<meta name="tag" content="plant, leaf, waterdroplet, water" />

$tags = get_meta_tags('yourfile.html');
$tags = array_map('trim', explode(',', $tags['tag']));

This will explode the words into an array, and remove any whitespace, you can then loop over this for outputting/whatever else:

example

foreach($tags as $k => $v) {
  echo $k . ': ' . $v . '<br />' . "\n";
}

Would output:

0: plant
1: leaf
2: waterdroplet
3: water


回答3:

You are getting the tags correctly, but not displaying them correctly.

You can't use echo on an array.

You can use var_dump to see the whole array that you have - which should show you how to access it in your code.



回答4:

You are making a mistake in setting the tags

<meta name="tag" content="xx" />
<meta name="tag" content="yz" />

When you execute get_meta_tags() on that, it will only show you the last value (in that case: yz)

So you need to put different names on the tags

eg

<meta name="tag1" content="yz" />
<meta name="tag2" content="yz" />


回答5:

The names must be unique. See the documentation of this function:

 If two meta tags have the same name, only the last one is returned.

So you can only have on meta-tag with name="tag", so better try a comma separated value for that.