简单的HTML dom css选择器无法正常工作
问题描述:
in reference to http://simplehtmldom.sourceforge.net/
I have this code:
require_once('simple_html_dom.php');
$x = '<span style="font-family:symbol">®</span>';
$dom = str_get_html($x);
$lis = $dom->find('[style=~font-family:symbol]');
print_r($lis);
Which tries to find tags whose style has the font-family:symbol in it using a css selector.
However this returns nothing.
What is wrong with my code?
答
Please read the doc carefully... The available attributes filter are :
+--------------------+----------------------------------------------------------------------------------------+
| Filter | Description |
+--------------------+----------------------------------------------------------------------------------------+
| [attribute] | Matches elements that have the specified attribute. |
| [!attribute] | Matches elements that don't have the specified attribute. |
| [attribute=value] | Matches elements that have the specified attribute with a certain value. |
| [attribute!=value] | Matches elements that don't have the specified attribute with a certain value. |
| [attribute^=value] | Matches elements that have the specified attribute and it starts with a certain value. |
| [attribute$=value] | Matches elements that have the specified attribute and it ends with a certain value. |
| [attribute*=value] | Matches elements that have the specified attribute and it contains a certain value. |
+--------------------+----------------------------------------------------------------------------------------+
So in your case, you can use the last one for example [the following is tested and it works]:
$lis = $dom->find('[style*="font-family:symbol"]');
答
You haven't quoted the font stuff in your XPath. The find()
call should be
$lis = $dom->find('[style=~"font-family:symbol"]');
^------------------^---- missing