问题描述
我想访问一个我添加到HTML文件中的某些元素的自定义属性,下面是一个 littleBox =somevalue
属性
I want to access a custom attribute that I added to some elements in an HTML file, here's an example of the littleBox="somevalue"
attribute
<div id="someId" littleBox="someValue">inner text</div>
以下内容不起作用:
foreach($html->find('div') as $element){
echo $element;
if(isset($element->type)){
echo $element->littleBox;
}
}
我看到一篇类似问题的文章,但是由于某种原因无法复制它这是我试过的:
I saw an article with a similar problem, but I couldn't replicate it for some reason. Here is what I tried:
function retrieveValue($str){
if (stripos($str, 'littleBox')){//check if element has it
$var=preg_split("/littleBox=\"/",$str);
//echo $var[1];
$var1=preg_split("/\"/",$var[1]);
echo $var1[0];
}
else
return false;
}
当我调用 retrieveValue()
函数,没有任何反应。是 $ element
(在上面的第一个PHP示例中)不是字符串?我不知道我是否错过了某些东西,但是它并没有返回任何东西。
When ever I call the retrieveValue()
function, nothing happens. Is $element
(in the first PHP example above) not a string? I don't know if I missed something but it's not returning anything.
这里是完整的脚本:
<?php
require("../../simplehtmldom/simple_html_dom.php");
if (isset($_POST['submit'])){
$html = file_get_html($_POST['webURL']);
// Find all images
foreach($html->find('div') as $element){
echo $element;
if(isset($element->type)!= false){
echo retrieveValue($element);
}
}
}
function retrieveValue($str){
if (stripos($str, 'littleBox')){//check if element has it
$var=preg_split("/littleBox=\"/",$str);
//echo $var[1];
$var1=preg_split("/\"/",$var[1]);
return $var1[0];
}
else
return false;
}
?>
<form method="post">
Website URL<input type="text" name="webURL">
<br />
<input type="submit" name="submit">
</form>
推荐答案
你尝试过:
$html->getElementById("someId")->getAttribute('littleBox');
您还可以使用SimpleXML:
You could also use SimpleXML:
$html = '<div id="someId" littleBox="someValue">inner text</div>';
$dom = new DOMDocument;
$dom->loadXML($html);
$div = simplexml_import_dom($dom);
echo $div->attributes()->littleBox;
我建议反对使用正则表达式解析html ,但不应该部分如下:
I would advice against using regex to parse html but shouldn't this part be like this:
$str = $html->getElementById("someId")->outertext;
$var = preg_split('/littleBox=\"/', $str);
$var1 = preg_split('/\"/',$var[1]);
echo $var1[0];
另请参阅这个答案
这篇关于PHP简单HTML DOM解析器:访问自定义属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!