如何将字符串从php变量传递到xml请求中?

How to pass a string from a php variable into an xml request?

提问人:Rediska 提问时间:10/5/2023 最后编辑:BarmarRediska 更新时间:10/5/2023 访问量:53

问:

我可能很愚蠢地写了我的问题,但我尽了我所能,我提前道歉)

我有一个XML文件。 我需要运行这样的查询:

$xml->shop->offers->offer

问题是我从变量中获取此路径:

$path = 'shop->offers->offer'

但它不会像这样工作:

$xml = simplexml_load_file('example.com');
$exampleElement = $xml->$path;

如何修复代码使其正常工作?

php xml simplexml

评论

0赞 Barmar 10/5/2023
使用 explode 将字符串拆分为数组。然后使用循环来获取使用该列表的每个嵌套属性。
0赞 Nigel Ren 10/5/2023
看看 XPath,因为它使用了类似的东西。
0赞 Rediska 10/5/2023
@barmar,你能举个例子吗?我将拆分数组,但是如何在此查询中使用foreach?$path = explode( "->", $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);