简体   繁体   English

用PHP生成DOMXPath联合提取

[英]DOMXPath union extract with PHP

I'm trying to get img and the div which is coming after the div which contains that img , all in one query. 我试图让imgdiv这是后即将到来div其中包含img ,都在同一个查询。 So I did this: 所以我这样做:

$nodes = $xpath->query('//div[starts-with(@id, "someid")]/img | 
//div[starts-with(@id, "someid")]/following-sibling::div[@class="spec_class"][1]/text()');

Now, I'm able to get the attributes of img tag, but I can't get the text of the following sibling. 现在,我可以获取img标签的属性,但是无法获取以下同级的文本。 If I separate the query (two queries - first for the img and second query for the sibling) it works. 如果我分开查询(两个查询-第一个查询img和第二个查询同级),则可以工作。 But how can I do this with only one query? 但是,如何仅执行一个查询呢? By the way, there is no error in the syntax. 顺便说一句,语法没有错误。 But somehow the union doesn't work or maybe I'm not extracting the sibling content right. 但是不知何故工会不起作用,或者也许我没有提取同级内容权利。

Here's the markup (which repeats many times with another text and id="someid_%randomNumber% ) 这是标记(它与另一个文本和id="someid_%randomNumber%重复多次)

<div id="someid_1">
    <img src="link_to_image.png" />
    ...some text...
</div>

<div>...another text...</div>

<div class="spec_class">
...Important text...
</div>

I want to get in one query both link_to_image.png and ...Important text... 我想同时查询link_to_image.png...重要文本...

Your query seems correct. 您的查询似乎正确。

Example XML: XML示例:

<div>
    <div id="someid-1"><img src="foo"/></div>
    <div class="spec_class">bar</div>
    <div class="spec_class">baz</div>
</div>

Example PHP Code: 示例PHP代码:

$dom = new DOMDocument;
$dom->loadXml($xhtml);
$xpath = new DOMXPath($dom);
foreach ($xpath->query('//div…') as $node) {
    echo $dom->saveXML($node);
}

Outputs ( demo ): 输出( 演示 ):

<img src="foo"/>bar

Note that you will have to iterate the DOMNodeList returned by the XPath query. 请注意,您将必须迭代XPath查询返回的DOMNodeList。

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

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