简体   繁体   English

使用domXpath在div中选择输入类型的文本值

[英]select input type text values inside a div using domXpath

i am trying access values of textbox which is inside DIV using domXpath. 我正在尝试使用domXpath访问DIV中的文本框的值。

basically, i have multiple DIVs and each DIV contains some input type text and it has some values in it. 基本上,我有多个DIV,每个DIV包含一些输入类型的文本,并且其中包含一些值。

i want to create an array and map it with its parent DIV 我想创建一个数组并将其与其父DIV映射

my sample HTML code: 我的示例HTML代码:

<div class="div_common_class">
    <div class="content_area">
        <div class="field_name">this is first</div>
    </div>

    <div class="input_area">
        <input type="text" name="" value="111" />
    </div>
</div>

<div class="div_common_class">
    <div class="content_area">
        <div class="field_name">this is second</div>
    </div>

    <div class="input_area">
        <input type="text" name="" value="222" />
    </div>
</div>

PHP code: PHP代码:

$dom = new DomDocument;
@$dom->loadHTML($html);

$xpath = new DOMXpath($dom);
$result = $xpath->query('//div[contains(@class, "div_common_class")]');

from the above PHP code i only get the values of the DIV, but not getting values of input type text. 从上面的PHP代码中,我仅获取DIV的值,而未获取输入类型文本的值。

and output something like: 并输出如下内容:

this is first 111 这是第一111

this is second 222 这是第二222

Your xpath gets the right divs, but you still need to get the values. 您的xpath获取正确的div,但是您仍然需要获取值。

You could use getElementsByTagName and use a foreach or get the elements by item like this example: 您可以使用getElementsByTagName并使用foreach或按item获取元素,例如以下示例:

$results = $xpath->query('//div[contains(@class, "div_common_class")]');
foreach ($results as $result) {
    echo sprintf("<b>%s %s</b><br>",
        $result->getElementsByTagName("div")->item(1)->textContent,
        $result->getElementsByTagName("input")->item(0)->getAttribute("value"));
}

That would give you: 那会给你:

this is first 111 这是第一111

this is second 222 这是第二222

Output php 输出PHP

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM