出现这个错误
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'];
}
如果你想用 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());
关于xpath php 属性不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12271480/