具有XML和XPath的Symfony DomCrawler - php

我正在尝试获取所有title元素并将其保存在数组中。

XML:

<?xml version="1.0" encoding="UTF-8"?>
<mylist>
    <element>
        <id>1</id>
        <title>Example 1</title>
        <status>2</status>
        <my_status>2</my_status>
    </element>
    <element>
        <id>2</id>
        <title>Example 2</title>
        <status>1</status>
        <my_status>1</my_status>
    </element>
    <element>
        <id>3</id>
        <title>Example 3</title>
        <status>2</status>
        <my_status>6</my_status>
    </element>
    <element>
        <id>4</id>
        <title>Example 4</title>
        <status>3</status>
        <my_status>6</my_status>
    </element>
    <element>
        <id>5</id>
        <title>Example 5</title>
        <status>1</status>
        <my_status>6</my_status>
    </element>
</mylist>

PHP:

$crawler = new Crawler();
$crawler->addXmlContent($data);

$result = $crawler->filterXPath('/mylist/element[not(status=3) and my_status=6]/title/text()');

元素节点需要满足一些条件,因此调用$result->count()应该打印2(示例3和示例5),但是它打印0。

谢谢。

编辑:

找到解决方案后,XPath应该是:

$result = $crawler->filterXPath('//mylist/element[not(status=3) and my_status=6]/title/text()');

参考方案

来自filteXpath批注

 * The XPath expression is evaluated in the context of the crawler, which
 * is considered as a fake parent of the elements inside it.
 * This means that a child selector "div" or "./div" will match only
 * the div elements of the current crawler, not their children.

然后在方法$xpath = $this->relativize($xpath);内部应用修改路径的位置。

对我而言,最简单的解决方案是使用./mylist之类的相对路径。

但是,如果您能理解这里发生的事情,那么https://github.com/symfony/dom-crawler/blob/master/Crawler.php#L958绝对路径应该是可能的,

需要从the_content()获取所有<img>;在WordPress中? - php

我最近刚从博客网站将所有内容导入到wordpress中,我需要整理一些东西。我正在single.php中工作,我想从<a><img src=""/></a>获取每个the_content();。我的php充其量是一点伪劣。我知道这是发布该帖子的第一张图片,但是我需要类似的内容,它可以将the_conte…

使用XPath在PHP中提取XML - php

我有以下XML:<root> <level name="level1"> <!-- More children <level> --> </level> <level name="level2"> <!-- Some more childre…

如何在PHP中显示特殊字符 - php

我已经多次看到这个问题,但是分辨率不高。我有以下字符串:$string = "<p>Résumé</p>"; 我想打印或回显字符串,但是输出将返回<p>R�sum�</p>。因此,我尝试使用htmlspecialchars()或htmlentities()来输出&lt;p&g…

无法访问heredoc中的数组 - php

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not…

使用Ajax呈现html表 - php

我想知道如何实现以下项目其实我有一个php代码,可以渲染一张桌子<table id = "oldata" class ="table table-bordered"> <thead> <tr class ="success"> <th class="…