xpath php属性不工作?
获取此错误 对非对象调用成员函数attributes() 我已经找到了很多答案,但是没有一个能解决我的问题 以下是XML:xpath php属性不工作?,xpath,simplexml,php,Xpath,Simplexml,Php,获取此错误 对非对象调用成员函数attributes() 我已经找到了很多答案,但是没有一个能解决我的问题 以下是XML: <Routes> <Route type="source" name="incoming"> </Route> <Routes> 以下是PHP: $doc = new SimpleXMLElement('routingConfig.xml', null, true); class traverseXML
<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());
$doc=new simplexmlement('routingConfig.xml',null,true);
类遍历EXML{
函数getData(){
全球$doc;
$routeCount=count($doc->xpath(“Route”);//此值返回正确
$routeArr=array();
对于($i=1;$i路由[$i]->attributes()->name;
数组推送($routeArr,$name);
}
返回$ROUTEAR;
}
}
$traverseXML=新的traverseXML;
var_dump($traverseXML->getData());
我理解错误的意思,但它怎么会是非对象?我如何返回
路由/路由[1]
的名称属性?您的$doc
是
。试图从中获取->Routes
是试图获取的
<Routes>
<Routes>
此外,XML无效。Routes元素未关闭
此外,您不需要XPath。SimpleXML是可遍历的,因此您可以通过
foreach ($Routes->Route as $route) {
而attributes()
返回一个数组,因此您不能将->name
从中链接出来,但必须使用方括号来访问它。但无论如何,不必使用attributes()
,因为您可以通过方括号直接从SimpleXmlElements获取属性,例如
echo $route['name'];
下面是一个将打印“传入”的示例:
是的,只是那一行:)
至于你们班:
如果您想拥有一个类,则注入依赖项,例如do
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());
谢谢!实际上,我有正确的XML文档,但把粘贴搞砸了。这比我的路线干净多了。
$xml = <<< XML
<Routes>
<Route type="source" name="incoming"/>
</Routes>
XML;
$routes = simplexml_load_string($xml);
foreach ($routes->Route as $route) {
echo $route['name'];
}
$routeNames = array_map('strval', $Routes->xpath('/Routes/Route/@name'));
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());