提问人:Rediska 提问时间:10/5/2023 最后编辑:BarmarRediska 更新时间:10/5/2023 访问量:53
如何将字符串从php变量传递到xml请求中?
How to pass a string from a php variable into an xml request?
问:
我可能很愚蠢地写了我的问题,但我尽了我所能,我提前道歉)
我有一个XML文件。 我需要运行这样的查询:
$xml->shop->offers->offer
问题是我从变量中获取此路径:
$path = 'shop->offers->offer'
但它不会像这样工作:
$xml = simplexml_load_file('example.com');
$exampleElement = $xml->$path;
如何修复代码使其正常工作?
答:
1赞
masonthedev
10/5/2023
#1
您可以将路径拆分为其组件,并循环访问这些组件以浏览 SimpleXML 对象。
一种方法是使用 explode()。它是一个内置的 PHP 函数,用于根据指定的子字符串将字符串拆分为子字符串数组,输入字符串将在该子字符串处拆分。在这种情况下,它可用于将存储在 $path 变量中的路径拆分为组件数组,然后使用这些组件在 XML 结构中移动。
https://www.php.net/manual/en/function.explode.php
你可以试试......
// Split the path into its components
$pathComponents = explode('->', $path);
// Start with the root element
$currentElement = $xml;
// Loop thru the path components and navigate thru the XML
foreach ($pathComponents as $component) {
if (isset($currentElement->$component)) {
$currentElement = $currentElement->$component;
} else {
// You can throw an exception or handle it according to your needs
// in this example, I just broke out of the loop
break;
}
}
// $currentElement should now contain the desired XML element
https://www.php.net/manual/en/function.isset.php
评论
1赞
Rediska
10/5/2023
嗯,这就是我所做的。 接下来呢?如何使用 foreach?$path = explode( "->", $path);
0赞
masonthedev
10/5/2023
刚刚更新的答案。
1赞
Barmar
10/5/2023
#2
拆分路径,然后遍历它,获取每个嵌套属性。
$props = explode("->", $path);
$el = $xml;
foreach ($props as $prop) {
$el = $el->$prop;
}
var_dump($el);
评论
$path = explode( "->", $path);