【问题标题】:xpath php attributes not working?xpath php属性不起作用?
【发布时间】:2012-09-04 21:16:46
【问题描述】:

收到此错误

在非对象上调用成员函数 attributes()

我在 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 属性?

【问题讨论】:

    标签: xpath simplexml php


    【解决方案1】:

    您的$doc&lt;Routes&gt;。试图从中获取-&gt;Routes 就是试图获取

    <Routes>
        <Routes>
    

    你需要做$doc-&gt;Route[$i]。当您在文档根目录之后命名变量时,这样的错误会减少:

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

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

    此外,您不需要 XPath。 SimpleXML 是可遍历的,因此您可以通过执行

    来遍历所有路由
    foreach ($Routes->Route as $route) {
    

    attributes() 返回一个数组,因此您不能将-&gt;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'));
    

    是的,就这么一行:)

    至于你的班级:

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

    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

    【讨论】:

    • 谢谢!我实际上有正确的 XML 文档,但是把我的粘贴搞砸了。这比我的路线干净得多。
    猜你喜欢
    • 2013-05-08
    • 2019-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多