xpath php 属性不起作用?

标签 xpath simplexml php

出现这个错误

Call to a member function attributes() on a non-object

我在 SO 上找到了多个答案,但似乎没有一个能解决我的问题?

这是 XML:

<Routes>
    <Route type="source" name="incoming">
    </Route>
<Routes>

这是 PHP:

$doc = new SimpleXMLElement('routingConfig.xml', null, true);
class traverseXML {

    function getData() {
        global $doc;
        $routeCount = count($doc -> xpath("Route")); //this value returns correctly
        $routeArr = array();
        for ($i = 1; $i <= $routeCount; $i++) {

            $name = $doc -> Route[$i] -> attributes() -> name;

            array_push($routeArr, $name);

        }
        return $routeArr;

    }

    }
    $traverseXML = new traverseXML;
    var_dump($traverseXML -> getData());

我明白这个错误是什么意思,但它怎么不是一个对象?如何返回 Routes/Route[1]name 属性?

最佳答案

你的 $doc<Routes> .试图获得 ->Routes从它试图得到

<Routes>
    <Routes>

你需要做 $doc->Route[$i] .当您在文档根目录之后命名变量时,这样的错误不太常见:

$Routes = new SimpleXMLElement('routingConfig.xml', null, true);

此外,您的 XML 无效。 Routes 元素未关闭。

此外,您不需要 XPath。 SimpleXML 是可遍历的,因此您可以通过执行以下操作遍历所有路由

foreach ($Routes->Route as $route) {

attributes()返回一个数组,所以你不能链接 ->name关闭它,但必须使用方括号访问它。但没有必要使用 attributes()无论如何,因为您可以直接通过方括号从 SimpleXmlElements 获取属性,例如

echo $route['name'];

这是一个打印“incoming”的例子:

$xml = <<< XML
<Routes>
    <Route type="source" name="incoming"/>
</Routes>
XML;

$routes = simplexml_load_string($xml);

foreach ($routes->Route as $route) {
    echo $route['name'];
}

demo

如果你想用 XPath 做到这一点,你可以像这样将所有属性收集到一个数组中:

$routeNames = array_map('strval', $Routes->xpath('/Routes/Route/@name'));

是的,就是那一行:)

至于你的类(class):

Don't use global . Forget it exists.如果你想要一个类,请注入(inject)依赖项,例如做

class Routes
{
    private $routes;

    public function __construct(SimpleXmlElement $routes)
    {
        $this->routes = $routes;
    }

    public function getRouteNames()
    {
        return array_map('strval', $this->routes->xpath('/Routes/Route/@name'));
    }
}

$routes = new Routes(simplexml_load_string($xml));
print_r($routes->getRouteNames());

demo

关于xpath php 属性不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12271480/

相关文章:

c# - 从 XHTML 文档中去除特定标签(但保留其内容)的机制?

php - 当该帖子的标签等于一个主题时,不显示重复的帖子

XPATH 查询 : How to get two elements?

php - 在有效的 PHP query() XPath 中转换 Javascript XPath |标准化 JS XPath --> PHP

java - 使用 selenium webdriver 从网页中检索元描述的内容

php - 遍历 SimpleXML 对象 PHP

php - for 循环内对当前 SimpleXMLElement 对象的 Xpath 查询

php - file_get_contents 通过 php 失败,通过浏览器工作

javascript - 获取更改时选择输入的值

php - 无法使用返回的 JSON