php - 使用 XML 和 XPath 的 Symfony DomCrawler

标签 php xml symfony xpath domcrawler

我正在尝试获取所有 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 .

最佳答案

来自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绝对路径应该可以,我觉得

关于php - 使用 XML 和 XPath 的 Symfony DomCrawler,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39312143/

相关文章:

symfony - 什么在 Symfony2 的 bin 文件夹中创建符号链接(symbolic link)

symfony - KnpMenuBundle 不适用于 Bootstrap 4 导航栏

php - 如何使RewriteCond更改THE_REQUEST但不更改REQUEST_METHOD

php - TinyMCE SCRIPT5 : Access is denied. 同一域上的典型跨域错误

c++ - 我应该着手创建一个程序以将信息存储到文件中、编辑该文件中的信息并添加新信息的最佳方法是什么

java - 如何在首选项中更改 ListView 中的焦点颜色?

php - 注入(inject)依赖项 - Doctrine : Multiple repositories vs single entity manager

php - Behat,Laravel5 中的 MySql 连接错误 : 'PDOException' 'SQLSTATE[HY000] [2005] Unknown MySQL server host 'mysql' (2)'

php - 从后台更改网站背景图片?

xml - 它们是 Android Studio 的 "region-like"折叠功能吗